Java实现GB2312文件转UTF8文件

有些书带的光盘的源代码是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

posted on 2016-07-22 11:53  荷楠仁  阅读(5888)  评论(0编辑  收藏  举报

导航