檔案編碼格式轉換
阿新 • • 發佈:2019-02-17
package com.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; /** * 類描述: 批量轉換檔案編碼格式 */ public class EncodeConverter { // 原始檔編碼 private static String srcEncode = "gbk"; // 輸出檔案編碼 private static String desEncode = "utf-8"; /** * @param infile 原始檔路徑 * @param outfile 輸出檔案路徑 * @param from 原始檔編碼 * @param to 目標檔案編碼 * @throws IOException * @throws UnsupportedEncodingException */ public static void convert(String infile, String outfile, String from, String to) throws IOException, UnsupportedEncodingException { //BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(infile), from)); //PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), to))); InputStream ins = new FileInputStream(infile); OutputStream ous = new FileOutputStream(outfile); /*String reading; while ((reading = in.readLine()) != null) { out.println(reading); }*/ byte[] b = new byte[(int)new File(infile).length()]; while(ins.read(b, 0, b.length) != -1) { String tmp = new String(b,from); ous.write(tmp.getBytes(to)); } ous.close(); ins.close(); } public static void main(String[] args) { if(!(args.length == 2)){ System.out.println("[ 檔案編碼轉換錯誤 ]====================引數個數不正確"); } String infile = args[0]; String outfile = args[1]; File file = new File(infile); if(!file.exists()) { System.out.println("[ 檔案編碼轉換錯誤 ]====================" + file.getAbsolutePath()+" 不存在===================="); } try { convert(infile, outfile, srcEncode, desEncode); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }