0

This is my code :

FileWriter fw = new FileWriter(log,true);
BufferedWriter bw = new BufferedWriter(fw);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);

fw.close();
bw.close();
sw.close();
pw.close();

I want to change it to something like this :

BufferedWriter bw = new BufferedWriter(new FileWriter(log,true));
PrintWriter pw = new PrintWriter(new StringWriter());

bw.close();
pw.close();

Will this be correct, or will the missing close() calls cause problems?

tucuxi
  • 17,561
  • 2
  • 43
  • 74
Munbujang
  • 3
  • 3
  • 1
    From the documentation if `PrintWriter#close`: `Closes the stream and releases any system resources associated with it. Closing a previously closed stream has no effect.` – SomeJavaGuy Aug 27 '15 at 08:53

3 Answers3

2

To be sure the close is not forgotten you could use the try-with-resource statement

try (BufferedWriter bw = new BufferedWriter(new FileWriter(log, true));
        PrintWriter pw = new PrintWriter(new StringWriter())) {
    // do your processing here
} catch (IOException ex) {
    // do your exception handling
}

The compiler will add for your the appropriate code for the close().

SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • 1
    This is also safer in the case of exceptions being launched, since the streams will be closed regardless of exceptions --- which is not the case in any of the 2 proposed variants in the OP – tucuxi Aug 27 '15 at 09:15
0

When you close a BufferedWriter Object which takes a FileWriter Object in its constructor, then implicitly the FileWriter Object is also closed.

So to answer your question, both ways are fine and the same and it don't make any problem

Previous Answer

Best practice

Community
  • 1
  • 1
user1933888
  • 2,897
  • 3
  • 27
  • 36
0

Since Java 7 you can let java automatically close the resources for you. Take a look at the try with resources.

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
}
Januson
  • 4,533
  • 34
  • 42