批量文件编码转换(GBK/UTF-8/UNICODE etc)

本文介绍了一个使用Java实现的批量文件编码转换程序。该程序能够将指定文件夹内的所有文件从GBK编码转换为Unicode编码。注意单个文件不宜过大,以免造成内存溢出。建议将待转换文件置于工程目录下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

批量文件编码转换,JAVA源码:代码中的GBK为文件编码格式,Unicode为目标文件编码格式,根据个人实际情况切换编码。

warn:因为文件是一次性读取全部字符,所以单个文件大小不要太大,否则会内存溢出的。

做好文件备份。

因为eclipse或者其它IDE里的代码只能编辑当前工程目录下的文件夹或者文件,对于不属于workspace的File是没有权限写入的,we‘d better 把需要转码的文件夹放在工程目录下进行转换。’


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class C {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		File file=new File("E:\\workspace\\AA\\src\\src");
		try {
			transfer2Unicode(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//E:\mobileBeta\com.agree.abt.mob\platforms\android\src\cn\com\agree\amate
//		File file=new File("E:\\workspace\\AA\\src\\src\\android\\src\\cn\\com\\agree\\amate\\AMate.java");
//		InputStreamReader isr=new InputStreamReader(new FileInputStream(file), Charset.forName("unicode"));
//		char[] chars=new char[1];
//		while(isr.read(chars)!=-1){
//			System.out.print(chars[0]);
//		}
//		String unicode="阿萨德发生";
//		byte[] utf=unicode.getBytes(Charset.forName("UTF-8"));
//		System.out.println(new String(utf,Charset.forName("UTF-8")));
//		System.out.println(new String(unicode.getBytes(Charset.forName("unicode")),Charset.forName("unicode")));
//		File file=new File("E:\\workspace\\AA\\src\\src/unicode");
//		OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(file), Charset.forName("unicode"));
//		osw.write(new String(unicode.getBytes(Charset.forName("unicode")),Charset.forName("unicode")).toCharArray());
//		osw.flush();
//		osw.close();
//		File[] files=file.listFiles();
//		for(File everyFile:files){
//			if(everyFile.isFile()){
//				InputStreamReader isr=new InputStreamReader(new FileInputStream(everyFile), Charset.forName("GBK"));
//				StringBuffer sb=new StringBuffer();
//				char[] chars=new char[1];
//				while(isr.read(chars)!=-1){
//					sb.append(chars);
//				}
//				String str=new String(sb.toString().getBytes(Charset.forName("GBK")));
//				String unicode=new String(str.getBytes(Charset.forName("unicode")),Charset.forName("unicode"));
//				System.out.print(unicode);
//				
//			}
//		}
	}
	public static void transfer2Unicode(File file) throws IOException{
		if(file.exists()){
			if(file.isDirectory()){
				File[] files=file.listFiles();
				for(File unit:files){
					transfer2Unicode(unit);
				}
			}else{
				InputStreamReader isr=new InputStreamReader(new FileInputStream(file), Charset.forName("GBK"));
				StringBuffer sb=new StringBuffer("");
				char[] chars=new char[1];
				while(isr.read(chars)!=-1){
					sb.append(chars);
				}
				String str=new String(sb.toString().getBytes(Charset.forName("GBK")));
				String unicode=new String(str.getBytes(Charset.forName("unicode")),Charset.forName("unicode"));
//				File unicodeFile=new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("\\")-1)+"/"+file.getName());
				OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(file),Charset.forName("unicode"));
				System.out.println(unicode.toString());
				osw.write(unicode.toCharArray());
				osw.flush();
				osw.close();
				isr.close();
				}
		} 
	}
}


root@ubuntu:/home/sunrise/Desktop/ydlidar_ws# ros2 launch ydlidar_ros2_driver qc.py [INFO] [launch]: All log files can be found below /root/.ros/log/2025-07-22-18-34-39-945635-ubuntu-46942 [INFO] [launch]: Default logging verbosity is set to INFO Task exception was never retrieved future: <Task finished name='Task-2' coro=<LaunchService._process_one_event() done, defined at /opt/ros/foxy/lib/python3.8/site-packages/launch/launch_service.py:226> exception=InvalidLaunchFileError('py')> Traceback (most recent call last): File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_description_sources/any_launch_file_utilities.py", line 53, in get_launch_description_from_any_launch_file return loader(launch_file_path) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_description_sources/python_launch_file_utilities.py", line 62, in get_launch_description_from_python_launch_file launch_file_module = load_python_launch_file_as_module(python_launch_file_path) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_description_sources/python_launch_file_utilities.py", line 37, in load_python_launch_file_as_module loader.exec_module(mod) File "<frozen importlib._bootstrap_external>", line 844, in exec_module File "<frozen importlib._bootstrap_external>", line 981, in get_code File "<frozen importlib._bootstrap_external>", line 911, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/sunrise/Desktop/ydlidar_ws/install/ydlidar_ros2_driver/share/ydlidar_ros2_driver/launch/qc.py", line 19 SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xbc in position 0: invalid start byte The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_service.py", line 228, in _process_one_event await self.__process_event(next_event) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_service.py", line 248, in __process_event visit_all_entities_and_collect_futures(entity, self.__context)) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/utilities/visit_all_entities_and_collect_futures_impl.py", line 45, in visit_all_entities_and_collect_futures futures_to_return += visit_all_entities_and_collect_futures(sub_entity, context) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/utilities/visit_all_entities_and_collect_futures_impl.py", line 45, in visit_all_entities_and_collect_futures futures_to_return += visit_all_entities_and_collect_futures(sub_entity, context) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/utilities/visit_all_entities_and_collect_futures_impl.py", line 38, in visit_all_entities_and_collect_futures sub_entities = entity.visit(context) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/action.py", line 108, in visit return self.execute(context) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/actions/include_launch_description.py", line 130, in execute launch_description = self.__launch_description_source.get_launch_description(context) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_description_source.py", line 84, in get_launch_description self._get_launch_description(self.__expanded_location) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_description_sources/any_launch_description_source.py", line 53, in _get_launch_description return get_launch_description_from_any_launch_file(location) File "/opt/ros/foxy/lib/python3.8/site-packages/launch/launch_description_sources/any_launch_file_utilities.py", line 56, in get_launch_description_from_any_launch_file raise InvalidLaunchFileError(extension, likely_errors=exceptions) launch.invalid_launch_file_error.InvalidLaunchFileError: Caught exception when trying to load file of format [py]: (unicode error) 'utf-8' codec can't decode byte 0xbc in position 0: invalid start byte (qc.py, line 19)
最新发布
07-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值