1. 程式人生 > >eclipse中.java檔案批量修改字符集

eclipse中.java檔案批量修改字符集

src路徑下的.java檔案用eclipse中開啟全是亂碼,但是自己平時使用的是UTF-8字符集,單個修改幾十個原始碼檔案很累,能否批量修改呢? 

-----下面是將工程裡面為gbk編碼的檔案轉為utf-8的方法,其中

-----String content = convEncoding(value, "gbk", "utf-8");  是將gbk轉為utf-8,     out.write(content.getBytes("UTF-8"));  最後輸出utf-8

------同理若要從utf-8,z轉成gbk.只需要更改為 String content = convEncoding(value, "utf-8, "gbk"); out.write(content.getBytes("UTF-8"));  最後輸出     gbk

------具體程式碼如下:

package myBean;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.UnsupportedEncodingException;
import java.text.MessageFormat;

/**
 * 該類可以將工程裡面gbk編碼轉為utf-8的編碼
 * @author wb_zjttx
 *
 */
public class FileGBK2UTF8 {
    public static void main(String[] args) {  
        // 需要轉換的檔案目錄  
        String fromPath = "D:\\fileTest\\input";  
        // 轉換到指定的檔案目錄  
        String toPath = "D:\\fileTest\\output";  
        
        String [] array={fromPath,toPath};
        info("start transform [from path]={0} [to path]={1}", array);  
  
        // 遞迴取到所有的檔案進行轉換  
        transform(fromPath, toPath);  
    }  
  
    /** 
     * 把一個目錄中的檔案轉換到另一個目錄中 
     *  
     * @param fromPath 
     *            -- 來原始檔目錄 
     * @param toPath 
     *            -- 目標檔案目錄 
     * @return 
     */  
    public static boolean transform(String fromPath, String toPath) {  
        File ftmp = new File(fromPath);  
        if (!ftmp.exists()) {  
            info("轉換檔案路徑錯誤!",null);  
            return false;  
        }  
        String [] array={fromPath,toPath};
        info("frompath is [{0}], topath is [{1}]", array);  
  
        // 如果是檔案,則轉換,結束  
        if (ftmp.isFile()) {  
            byte[] value = fileToBytes(fromPath);  
            String content = convEncoding(value, "gbk", "utf-8");  
            return saveFileUtf8(toPath, content);  
        } else {  
            // 查詢目錄下面的所有檔案與資料夾  
            File[] childFiles = ftmp.listFiles();  
            for (int i = 0, n = childFiles.length; i < n; i++) {  
                File child = childFiles[i];  
                String childFrom = fromPath + "/" + child.getName();  
                String childTo = toPath + "/" + child.getName();  
  
                transform(childFrom, childTo);  
            }  
        }  
  
        return true;  
    }  
  
    /** 
     * 把檔案內容儲存到指定的檔案中,如果指定的檔案已存在,則先刪除這個檔案, 如果沒有則建立一個新檔案,檔案內容採用UTF-8編碼方式儲存。 
     * 如果指定的檔案路徑不存在,則先建立檔案路徑,檔案路徑從根目錄開始建立。 
     *  
     * @param fileName 
     *            -- 檔案路徑 
     * @param content 
     *            -- 檔案內容 
     * @return 
     */  
    public static boolean saveFileUtf8(String fileName, String content) {  
        if (fileName == null || fileName.length() == 0)  
            return false;  
        if (content == null)  
            return false;  
  
        // 路徑中的\轉換為/  
        fileName = fileName.replace('\\', '/');  
        // 處理檔案路徑  
        createPath(fileName.substring(0, fileName.lastIndexOf('/')));  
  
        File file = null;  
        FileOutputStream out = null;  
        try {  
            // 建立或修改檔案  
            file = new File(fileName);  
  
            if (file.exists()) {  
                file.delete();  
            } else {  
                file.createNewFile();  
            }  
  
            out = new FileOutputStream(file);  
            // 新增三個位元組標識為UTF-8格式,也是BOM碼  
            // out.write(new byte[]{(byte)0xEF,(byte)0xBB,(byte)0xBF});  
            out.write(content.getBytes("UTF-8"));  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
            return false;  
        } catch (IOException e) {  
            e.printStackTrace();  
            return false;  
        } finally {  
            if (out != null) {  
                try {  
                    out.flush();  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    return false;  
                }  
            }  
        }  
  
        return true;  
    }  
  
    /** 
     * 把檔案內容轉換為位元組陣列輸出。 
     *  
     * @param fileName 
     *            -- 檔名 
     * @return 
     */  
    public static byte[] fileToBytes(String fileName) {  
        FileInputStream ins = null;  
        ByteArrayOutputStream bos = null;  
        try {  
            // 建立檔案讀入流  
            ins = new FileInputStream(new File(fileName));  
            // 建立目標輸出流  
            bos = new ByteArrayOutputStream();  
  
            // 取流中的資料  
            int len = 0;  
            byte[] buf = new byte[256];  
            while ((len = ins.read(buf, 0, 256)) > -1) {  
                bos.write(buf, 0, len);  
            }  
  
            // 目標流轉為位元組陣列返回到前臺  
            return bos.toByteArray();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (ins != null) {  
                    ins.close();  
                    ins = null;  
                }  
                if (bos != null) {  
                    bos.close();  
                    bos = null;  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
        return null;  
    }  
  
    /** 
     * 檢查指定的檔案路徑,如果檔案路徑不存在,則建立新的路徑, 檔案路徑從根目錄開始建立。 
     *  
     * @param filePath 
     * @return 
     */  
    public static boolean createPath(String filePath) {  
        if (filePath == null || filePath.length() == 0)  
            return false;  
  
        // 路徑中的\轉換為/  
        filePath = filePath.replace('\\', '/');  
        // 處理檔案路徑  
        String[] paths = filePath.split("/");  
  
        // 處理檔名中沒有的路徑  
       /// StringBuilder sbpath = new StringBuilder();  
        StringBuffer sbpath = new StringBuffer();  
        for (int i = 0, n = paths.length; i < n; i++) {  
            sbpath.append(paths[i]);  
            // 檢查檔案路徑如果沒有則建立  
            File ftmp = new File(sbpath.toString());  
            if (!ftmp.exists()) {  
                ftmp.mkdir();  
            }  
  
            sbpath.append("/");  
        }  
  
        return true;  
    }  
  
    /** 
     * 取路徑中的檔名 
     *  
     * @param path 
     *            -- 檔案路徑,含檔名 
     * @return 
     */  
    public static String getFileName(String path) {  
        if (path == null || path.length() == 0)  
            return "";  
  
        path = path.replaceAll("\\\\", "/");  
        int last = path.lastIndexOf("/");  
  
        if (last >= 0) {  
            return path.substring(last + 1);  
        } else {  
            return path;  
        }  
    }  
  
    /** 
     * 字串的編碼格式轉換 
     *  
     * @param value 
     *            -- 要轉換的字串 
     * @param oldCharset 
     *            -- 原編碼格式 
     * @param newCharset 
     *            -- 新編碼格式 
     * @return 
     */  
    public static String convEncoding(byte[] value, String oldCharset,  
            String newCharset) {  
        OutputStreamWriter outWriter = null;  
        ByteArrayInputStream byteIns = null;  
        ByteArrayOutputStream byteOuts = new ByteArrayOutputStream();  
        InputStreamReader inReader = null;  
  
        char cbuf[] = new char[1024];  
        int retVal = 0;  
        try {  
            byteIns = new ByteArrayInputStream(value);  
            inReader = new InputStreamReader(byteIns, oldCharset);  
            outWriter = new OutputStreamWriter(byteOuts, newCharset);  
            while ((retVal = inReader.read(cbuf)) != -1) {  
                outWriter.write(cbuf, 0, retVal);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (inReader != null)  
                    inReader.close();  
                if (outWriter != null)  
                    outWriter.close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
  
        String temp = null;  
        try {  
            temp = new String(byteOuts.toByteArray(), newCharset);  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        // System.out.println("temp" + temp);  
        return temp;  
    }  
  
    /** 
     * 顯示提示資訊 
     *  
     * @param message 
     *            -- 資訊內容 
     * @param params 
     *            -- 引數 
     */  
    private static void info(String message, Object[]params) {  
        message = MessageFormat.format(message, params);  
  
        System.out.println(message);  
    }  
}