Difference between java.io.PrintWriter and java.io.BufferedWriter?

后端 未结 8 1351
南笙
南笙 2020-12-02 06:04

Please look through code below:

// A.class
File file = new File(\"blah.txt\");
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new P         


        
相关标签:
8条回答
  • 2020-12-02 06:59

    In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,

    Note: Text content in the code blocks is automatically word-wrapped

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

    will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.

    0 讨论(0)
  • 2020-12-02 07:03

    As said in TofuBeer's answer both have their specialties. To take the full advantage of PrintWriter (or any other writer) but also use buffered writing you can wrap the BufferedWriter with the needed one like this:

    PrintWriter writer = new PrintWriter(
                             new BufferedWriter (
                                 new FileWriter("somFile.txt")));
    
    0 讨论(0)
提交回复
热议问题