用java将GBK工程转为uft8的方法实例
本文介绍了用java将GBK工程转为uft8,分享给大家,具体如下:
windows下的默认编码为GBK还有gb2312,如何把gbk的java工程转为utf8的呢,如果直接修改工程编码,其实里面的java文件中中文是会乱码的,写了个批量转换java工程的程序,消遣一下。
为什么要转码?
有些老的项目,或者朋友的项目之前没注意在windows上不是utf8,而你有需要看注释或者什么,总不能一个文件一个文件的去改编码属性吧。
本程序试用范围
gbk的代码,或者gb2312的工程均可以转换
编码转换的思路
本来想做成一个通用的会自动检测编码,自动转换的程序。但是由于判断编码类型不准,所以做成了针对GBK的转换。
- 制定gbk编码把文件流读进来,加载到内存,转为String类型的内容
- 将String内容转为utf8的String
- 将String内容写入文件
核心代码:
publicclassTransferProject{
publicstaticvoidtransferFile(StringpathName,intdepth)throwsException{
FiledirFile=newFile(pathName);
if(!isValidFile(dirFile))return;
//获取此目录下的所有文件名与目录名
String[]fileList=dirFile.list();
intcurrentDepth=depth+1;
for(inti=0;i
publicclassFileUtils{
publicstaticvoidwriteByBufferedReader(Stringpath,Stringcontent){
try{
Filefile=newFile(path);
file.delete();
if(!file.exists()){
file.createNewFile();
}
FileWriterfw=newFileWriter(file,false);
BufferedWriterbw=newBufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticStringreadFileByEncode(Stringpath,StringchatSet)throwsException{
InputStreaminput=newFileInputStream(path);
InputStreamReaderin=newInputStreamReader(input,chatSet);
BufferedReaderreader=newBufferedReader(in);
StringBuffersb=newStringBuffer();
Stringline=reader.readLine();
while(line!=null){
sb.append(line);
sb.append("\r\n");
line=reader.readLine();
}
returnsb.toString();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。