Write a line of text to File

suggest change

This code writes the string to a file. It is important to close the writer, so this is done in a finally block.

public void writeLineToFile(String str) throws IOException {
  File file = new File("file.txt");
  BufferedWriter bw = null;
  try {
    bw = new BufferedWriter(new FileWriter(file));
    bw.write(str);
  } finally {
    if (bw != null) {
      bw.close();
    }
  }
}

Also note that write(String s) does not place newline character after string has been written. To put it use newLine() method.

Java 7 adds the java.nio.file package, and try-with-resources:

public void writeLineToFile(String str) throws IOException {
    Path path = Paths.get("file.txt");
    try (BufferedWriter bw = Files.newBufferedWriter(path)) {
        bw.write(str);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


BufferedWriter:
* Write a line of text to File

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
76 BufferedWriter
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap