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

相关文章:

  • 2021-11-16
  • 2022-02-04
  • 2021-09-21
  • 2022-12-23
  • 2021-07-05
  • 2022-12-23
猜你喜欢
  • 2021-07-30
  • 2021-05-17
  • 2022-12-23
  • 2022-01-28
  • 2021-07-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案