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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM