Difference between PrintWriter and FileWriter class

后端 未结 4 1639
灰色年华
灰色年华 2021-02-05 21:17
try{

    File file = new File(\"write.txt\");
    FileWriter writer = new FileWriter(file);

    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.prin         


        
相关标签:
4条回答
  • 2021-02-05 21:50

    Although both of these internally uses a FileOutputStream , the main difference is that PrintWriter offers some additional methods for formatting like println and printf.

    code snippets:

    public PrintWriter(File file) throws FileNotFoundException {
         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
         false);
    }
    
    
    public FileWriter(File file) throws IOException {
           super(new FileOutputStream(file));
    }
    

    Major Differences :

    1. FileWriter throws IOException in case of any IO failure.
    2. None of the PrintWriter methods throws IOException, instead they set a boolean flag which can be obtained using checkError().
    3. PrintWriter comes with an option of autoflush while creation(default is without autoflush) which will flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.
    0 讨论(0)
  • 2021-02-05 21:50

    PrintWriter gives you some handy methods for formatting like println and printf. So if you need to write printed text - you can use it. FileWriter is more like "low-level" writer that gives you ability to write only strings and char arrays. Basically I don't think there is a big difference what you choose.

    0 讨论(0)
  • 2021-02-05 21:58

    While FileWriter has only a basic set of methods, PrintWriter has a rich set of convinience methods, one of them is in your example - PrintWriter.println.

    You should also keep in mind that "methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError()"

    0 讨论(0)
  • 2021-02-05 22:02

    From the source what PrintWriter does when you pass a File is to open it in a buffered way

    public PrintWriter(File file) throws FileNotFoundException {
        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
             false);
    }
    

    if you pass it a FileWriter, it will open it, without buffering

    public FileWriter(File file) throws IOException {
        super(new FileOutputStream(file));
    }
    

    This means that the first example can be slightly more efficient. However I would use the File without the FileWriter because to me it is simpler.

    0 讨论(0)
提交回复
热议问题