很多时候从网上下载到的代码是GBK编码,也就是eclipse默认的编码。而在项目中,有时会规定用utf-8的编码。
如果一个一个文件转换是很麻烦的,特别是文件数量多了以后。自己写了一个转换的小程序,贴出来,共享一下,希望能有用:
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileFilter;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- /*
- * 提供过滤,只转换JAVA文件
- * */
- class JavaFileFilter implements FileFilter{
- @Override
- public boolean accept(File pathname) {
- if(pathname.isDirectory()||pathname.getName().endsWith(".java"))
- return true;
- return false;
- }
- }
- public class GBKtoUTF8 {
- public void visit(File source,File dest){
- if(source.isDirectory()){ //如果是目录,则在dest目录下创建相同的目录
- new File(dest.getAbsolutePath()+File.separator+source.getName()).mkdirs();
- File[] files=source.listFiles(new JavaFileFilter());
- for (File file : files) {
- visit(file,new File(dest.getAbsolutePath()+File.separator+source.getName()));
- }
- }else{
- //如果是文件,则进行转换
- transform(source,dest);
- }
- }
- public void transform(File source,File dest){
- try {
- BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(source),"gbk"));
- BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(dest.getAbsolutePath()+File.separator+source.getName())),"utf-8"));
- String line=null;
- while((line=reader.readLine())!=null){
- writer.write(line+"\n");
- }
- reader.close();
- writer.close();
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- public static void main(String[] args) {
- new GBKtoUTF8().visit(new File("E:/ProjectName"),new File("E:/transfor"));
- }
- }