0

What if in the next bit of code I am going to substitute (new FileWriter with (new PrintWriter

pw = new PrintWriter(new BufferedWriter(new FileWriter  ("xanaduindeed.txt")));

pw = new PrintWriter(new BufferedWriter(new PrintWriter ("xanaduindeed.txt")));

Both of them work fine, however I would like to know which of the two optimize the memory usage. (if either of the two is actually better) Thanks in advance.

Rollerball
  • 12,618
  • 23
  • 92
  • 161
  • 1
    Isn't `pw = new PrintWriter(new BufferedWriter(new PrintWriter("xanaduindeed.txt")));` the same as `pw = new PrintWriter("xanaduindeed.txt");` ? – Bernhard Barker Apr 25 '13 at 13:13

3 Answers3

3

In Oracle's JVM:

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

PrintWriter's notable characteristic is to flush output on every newline (LF or CR or CRLF). Lowest memory footprint would be a bare FileWriter, but buffering gives a notable improvement in I/O performance.

Tadas S
  • 1,955
  • 19
  • 33
1

The main thing I'd worry about is exception handling being different for both cases. Check out this older answer here

In either case though, be careful with the encoding! You're taking yout system's default, so something you write on your computer might be misread in another

Community
  • 1
  • 1
Miquel
  • 15,405
  • 8
  • 54
  • 87
0

The best solution is

new PrintWriter ("xanaduindeed.txt")));

it uses BufferedWriter internally and writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. You dont need to try and optimize it further.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275