CSDNRGY 2017-02-22 01:55 采纳率: 88.6%
浏览 1850
已采纳

为什么要把FileWriter转换成BufferedWriter?

我知道bufferWriter具有缓冲的功能
其他的就不太清楚了
感觉把FileWriter转换成BufferedWriter代码看起来很丑

 public class Test {

    public static void main(String[] args) throws IOException {
        f1();
        f2();
    }

    static void f1() throws IOException {
        FileWriter fileWriter = new FileWriter("src/t.txt", true);
        fileWriter.write("bString");
        fileWriter.close();
    }

    static void f2() throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/t.txt", true));
        bufferedWriter.write("aString");
        bufferedWriter.close();
    }
}

如果说性能上有差异,怎么能测试出,俩者性能上存在差异?

还有这种写法,这么写的目的是什么?

  PrintWriter out  = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

  • 写回答

3条回答 默认 最新

  • engchina 人工智能领域优质创作者 2017-02-22 04:26
    关注

    FileWriter: You were going to write to the file a number of times -- especially many short writes like a list of a thousand names or something like that
    BufferedWriter:Send only large chunks of data to the FileWriter.Writing one large chunk to a file is more efficient than many small ones because each call to FileWriter.write() involves a call to the operating system, and those are slow

    Below was a simple test.

    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class TestBuffer {
    
        public static void main(String[] args) throws IOException {
    
            long startTime = System.currentTimeMillis();
            f1();
            long stopTime = System.currentTimeMillis();
            long elapsedTime = stopTime - startTime;
            System.out.println(elapsedTime);
    
            startTime = System.currentTimeMillis();
            stopTime = System.currentTimeMillis();
            f2();
            elapsedTime = stopTime - startTime;
            System.out.println(elapsedTime);
        }
    
        static void f1() throws IOException {
            FileWriter fileWriter = new FileWriter("src/t1.txt", true);
            for (int i = 0; i < 10000000; i++) {
                fileWriter.write("bString");
            }
            fileWriter.close();
        }
    
        static void f2() throws IOException {
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("src/t2.txt", true));
            for (int i = 0; i < 10000000; i++) {
                bufferedWriter.write("aString");
            }
            bufferedWriter.close();
        }
    }
    

    output

    639
    0
    

    What's more, BufferedWriter has newLine() method to write new line(\n or \r\n) according to OS.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?