In Java, we can use BufferedWriter to write content into a file.
// jdk 7
try (FileWriter writer = new FileWriter("app.log");
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
Note
If possible, uses
Files.writeinstead, one line, simple and nice.Read Files.write examples
List<String> list = Arrays.asList("Line 1", "Line 2");
Files.write(Paths.get("app.log"), list);
1. BufferedWriter
Write content into a file.
WriteFileBufferedWriter1.java
package com.favtuts.io.file;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileBufferedWriter1 {
public static void main(String[] args) {
String content = "This is the content to write into file\n";
// If the file doesn't exists, create and write to it
// If the file exists, truncate (remove all content) and write to it
try (FileWriter writer = new FileWriter("app.log");
BufferedWriter bw = new BufferedWriter(writer)
) {
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
}
Output:
app.log
This is the content to write into file
For Append mode, pass a true as second argument in FileWriter
// If the file exists, append to it
try (FileWriter writer = new FileWriter("app.log", true);
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
2. BufferedWriter (Old School Style)
Before the JDK 7 try-resources, we need to handle the close() manually. A painful memory, let see this :
WriteFileBufferedWriter2.java
package com.favtuts.io.file;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileBufferedWriter {
public static void main(String[] args) {
writeFileBufferedWriterClassic();
}
private static void writeFileBufferedWriterClassic() {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String content = "This is the content to write into file\n";
fw = new FileWriter("app.log");
//fw = new FileWriter("app.log", true); Append mode
bw = new BufferedWriter(fw);
bw.write(content);
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
System.err.format("IOException: %s%n", ex);
}
}
}
}
Output
app.log
This is the content to write into file
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-io/file