近日从网上下载了一个仿携程的源码,准备学习。打开工程后,发现很多中文的注释都是乱码,按理来说影响不是太大,但是总归是看着不爽,于是上网搜寻了很多办法,来解决这个问题。
方法一:直接使用windows自带的文本编辑器,将源码另存一下,选定需要编码的格式,一般选UTF-8,即可。但是缺陷在于,任何一个工程下属的文件都非常多,这样一个一个改起来耗费的时间非常长,只针对于文件数量比较少的可以采用这种方法。
方法二:打开Eclipse后,选中该源文件,然后右键->properties->resource->text file encoding,然后选择需要格式,但是可选择的格式很有限,并不能满足要求。
方法三:打开Eclipse后,windows->preferences->general->content types->text->java source->default encoding,输入原来的编码方式。这种方法最简单也是支持格式比较多的方法。
我在没有找到方法三的情况下,一怒之下决定自己写一个转码程序。该程序可以自动搜索给定的路径下的所有文件,并将原始的ANSI(GBK)编码的文件转换为UTF-8文件。编程过程中学到的知识包括:1、各种输入输出流只是建立一个读写的通道,规定这个通道是以什么方式,什么编码来传输的。2、换行符在以前的概念里都是'\n'来表示的,但是在java里是用"\r\n"来表示的。因此要在读取到的一行一行的数据中间添加"\r\n",否则打印的时候没法打印出换行符。代码如下图:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class AnsiToUtf8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("请输入文件目录");
String pathname = sc.nextLine() ;
if(pathname.equals("ok")) {
sc.close();
break;
}else {
File file = new File(pathname);
convertion(file);
}
}
}
public static int convertion(File file) {
String filepath = null;//覆盖原始文件路径
BufferedReader indata = null;
PrintWriter outdata = null;
File nextFile = null;
if(file.isDirectory()) {
String nextpathname = null;
String[] filelist = null;
filelist = file.list();
for(int i=0;i<filelist.length;i++) {
System.out.println(filelist[i]);
//接下来递归进入下一层文件目录
nextpathname = file.getPath()+'\\'+filelist[i];
nextFile = new File(nextpathname);
convertion(nextFile);
}
System.out.println(file.getPath());
}else if(file.isFile()){
filepath = file.getPath();
try {
indata = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));
String readData = "";
String temp = null;
while((temp = indata.readLine())!=null) {
readData = readData+"\r\n"+temp ;
}
//创建输出路径
outdata =new PrintWriter(new BufferedWriter( new OutputStreamWriter(new FileOutputStream(filepath), "UTF-8")));
outdata.println(readData);
indata.close();
outdata.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("读取失败");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("编码失败");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
return -1;
}
}