天天看點

轉碼java_Java實作GBK轉碼到UTF-8(檔案)

packagecom.liruilong.demotext.service.utils;import java.io.*;

public classEncodingUtil {public static voidgbkAndUtf8(File file) {if (!file.exists() ||file.isDirectory()) {

System.out.println("輸入路徑不對");

}else{//以GBK格式,讀取檔案

FileInputStream fileInputStream = null;

InputStreamReader inputStreamReader= null;

BufferedReader bufferedReader= null;

FileOutputStream fileOutputStream= null;

OutputStreamWriter outputStreamWriter= null;try{

fileInputStream= newFileInputStream(file);

inputStreamReader= new InputStreamReader(fileInputStream, "GBK");

bufferedReader= newBufferedReader(inputStreamReader);

String str= null;//建立StringBuffer字元串緩存區

StringBuffer stringBuffer = newStringBuffer();//通過readLine()方法周遊讀取檔案

while ((str = bufferedReader.readLine()) != null) {//使用readLine()方法無法進行換行,需要手動在原本輸出的字元串後面加"\n"或"\r"

str += "\n";

stringBuffer.append(str);

}

String str2=stringBuffer.toString();//以UTF-8格式寫入檔案,file.getAbsolutePath()即該檔案的絕對路徑,false代表不追加直接覆寫,true代表追加檔案

fileOutputStream = new FileOutputStream(file.getAbsolutePath(), false);

outputStreamWriter= new OutputStreamWriter(fileOutputStream, "UTF-8");

outputStreamWriter.write(str2);

outputStreamWriter.flush();

}catch(IOException e) {

e.printStackTrace();

}finally{

allClose(outputStreamWriter, fileOutputStream, bufferedReader, inputStreamReader, fileInputStream);

}

}

}public static voidallClose(Closeable... closeables) {for(Closeable closeable : closeables) {try{

closeable.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

繼續閱讀