欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java中指定编码操作文本文件

程序员文章站 2024-02-23 14:15:16
...

1.使用指定编码操作文本文件

    /**
     * 使用指定编码操作文本文件
     * 通过高效字符流拷贝文本文件,一行一行读取
     */
    @Test
    public void copyFile04(){
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            String sourceFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\a.txt";
            String targetFileUrl = "C:\\Users\\admin\\Desktop\\testIO\\b.txt";
            //可以指定编码集,防止乱码
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileUrl),"utf-8"));
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFileUrl),"utf-8"));
            //使用默认的编码集进行操作,utf-8
            //reader = new BufferedReader(new FileReader(sourceFileUrl));
            //writer = new BufferedWriter(new FileWriter(targetFileUrl));
            String line;
            while ((line=reader.readLine())!=null){
                writer.write(line);
                writer.newLine();//输出换行符
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //在finally中关闭开启的流
            if (reader!=null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (writer!=null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }