Difference between PrintWriter and FileWriter clas

2020-06-03 03:18发布

try{

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

    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.println("pqr");
    printWriter.println("jkl");
    printWriter.close();

    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println("abc");
    printWriter.println("xyz");
    printWriter.close();
}

I don't understand what is difference bet'n these two way. In which scenario i should use printWriter and fileWriter.

标签: java file-io
4条回答
我命由我不由天
2楼-- · 2020-06-03 04:03

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.
查看更多
老娘就宠你
3楼-- · 2020-06-03 04:05

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.

查看更多
淡お忘
4楼-- · 2020-06-03 04:08

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()"

查看更多
闹够了就滚
5楼-- · 2020-06-03 04:17

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.

查看更多
登录 后发表回答