有些書帶的光盤的源代碼是GB2312編碼.通常IDE的編碼是UTF8.這樣直接導入IDE會亂碼. 這時候就需要把GB2312的文件轉成UTF8的文件.轉化的思路很簡單,讀入流初始化的時候告訴jvm是GB2312編碼,讀入后jvm內部會轉成UNICODE,寫出的時候再告訴jvm以UTF8的形式寫出即可.源代碼如下:
import java.io.*;
public class Convert {
private void process() {
String srcFile = "D:\\test1\\MatrixState.java";//gb2312編碼
String destFile = "D:\\test2\\MatrixState.java";//UTF8編碼
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
is = new FileInputStream(srcFile);
isr = new InputStreamReader(is, "gb2312");
br = new BufferedReader(isr);
os = new FileOutputStream(destFile);
osw = new OutputStreamWriter(os, "UTF-8");
bw = new BufferedWriter(osw);
String line;
for (line = br.readLine(); line != null; line = br.readLine()) {
System.out.println("line=" + line);
bw.write(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Convert().process();
}
}
參考資料:
http://stackoverflow.com/questions/33535594/converting-utf8-to-gb2312-in-java