java轉格式代碼

在公司以前是windows,默認編碼格式是gbk,現在開發ios應用,換了mac mini最近很被編碼格式困然,windows默認是gbk,mac不支持這個東西。
回到家裏,家裏電腦是Ubuntu,也一樣是亂碼,上網找了一段代碼,復制到eclipse,發現有bug,修好bug,把代碼貼上來吧:

import java.io.BufferedReader;  
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.io.PrintWriter;  


public class UTF8Parser {

    public static void main(String[] args) { 

        File srcDir = new File("/home/yeshen/Documents/Folder/CmsManager"); 

        if(!srcDir.isDirectory()){  
            return;  
        }  
        File[] fs = srcDir.listFiles();  

        try {  
            new UTF8Parser().parse(fs);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
        System.out.print("finish");
    }  


    private void parse(File[] fs) throws IOException {  
        for(File file:fs){  
            if(!file.isDirectory() ){  
                if(file.getName().contains("java")){
                    File p =new File( file.getParent());
                    if(!p.exists()){p.mkdirs();}
                    String path = file.getAbsolutePath().replace("/Folder/CmsManager", "/Folder/CmsManagers");
                    File destFile = new File(path);
                    parse2UTF_8(file,destFile);
                }
            }else{  
                parse(file.listFiles());  
            }  
        }  
    }  

    private void parse2UTF_8(File file,File destFile) throws IOException {  
        StringBuffer msg = new StringBuffer();  
        PrintWriter ps = new PrintWriter(new OutputStreamWriter(new FileOutputStream(destFile,false),"utf-8"));  
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));  

        String line = br.readLine();  
        while(line!=null){  
            msg.append(line).append("\r\n");  
            line = br.readLine();  
        }  
        ps.write(msg.toString());  
        br.close();  
        ps.flush();  
        ps.close();  
    }  

}  

你可能感兴趣的:(編碼)