PrintWriter vs FileWriter in Java

后端 未结 7 1130
谎友^
谎友^ 2020-11-29 19:36

Are PrintWriter and FileWriter in Java the same and no matter which one to use? So far I have used both because their results are the same. Is there some special cases where

7条回答
  •  余生分开走
    2020-11-29 19:53

    Both of these use a FileOutputStream internally:

    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));
    }
    

    but the main difference is that PrintWriter offers special methods:

    Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

    Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.

提交回复
热议问题