Difference between PrintWriter and FileWriter class

后端 未结 4 1634
灰色年华
灰色年华 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.

提交回复
热议问题