I’m writing some code using java.io.BufferedWriter
the first thing I tried was:
String filename = new String("test.txt");
Charset charset = new Charset("US-ASCII");
try {
BufferedWriter bw = Files.newBufferedWriter(Paths.get(filename), charset);
bw.write("hello");
} catch (IOException e) {
System.out.println(e);
}
which outputted an empty test.txt
seeing an example, in the following format, I tried:
String filename = new String("test.txt");
Charset charset = new Charset("US-ASCII");
try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(filename), charset)){
bw.write("hello");
} catch (IOException e) {
System.out.println(e);
}
which outputted a text file with the first line “hello”.
What does this form mean, and why does it work while my first attempt did not?
This is called “try-with-resources” in Java 7, your BufferedWriter will be closed automatically if you fixed it as
See http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html