Writing a File in Java

Different ways to write text files in Java.

BufferedWriter

Use java.io.BufferedWriter to write text to character-output stream. This class buffers characters to provide a more efficient writing.

1
2
3
4
5
6
7
public static void writeFile(String filename, String content) {
try( BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(content);
} catch(IOException e) {
e.printStackTrace();
}
}

An easier way to create BufferedWriter is to use Files.newBufferedWriter method

1
try( BufferedWriter writer = Files.newBufferedWriter(Path.of(filename), StandardCharsets.UTF_8)) { ... }

If you need to write the file to a directoy that may not be exist yet, then you may need to create nonexistent directories first.

1
2
3
4
5
try {
Files.createDirectories(Path.of("path/newpath/"));
} catch (IOException e) {
e.printStackTrace();
}

Append String to existing File

You can append content at the end of the file if you set the append parameter to be true when creating the FileWriter.

1
2
3
4
5
6
7
public static void appendFile(String filename, String content) {
try( BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true))) {
writer.write(content);
} catch(IOException e) {
e.printStackTrace();
}
}

Append to file using Files.newBufferedWriter method

1
2
3
4
5
6
7
public static void appendFile(String filename, String content) {
try( BufferedWriter writer = Files.newBufferedWriter(Path.of(filename), StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(content);
} catch(IOException e) {
e.printStackTrace();
}
}

PrintWriter

If you need to print formatted text, then use java.io.PrintWriter

1
2
3
4
5
6
7
8
public static void writeFile(String filename, String content) {
try( PrintWriter printWriter = new PrintWriter(new FileWriter(filename))) {
printWriter.println("Hello World");
printWriter.printf("There are %d apples here", 15);
} catch(IOException e) {
e.printStackTrace();
}
}

Write Uing Files Class

java.nio.file.Files class provides static methods to write files.

use Files.write​(Path path, byte[] bytes, OpenOption... options) method to write bytes.

1
2
3
4
5
6
7
public static void writeFile(String filename, String content) {
try {
Files.write(Path.of(filename), content.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}

use writeString​(Path path, CharSequence csq, Charset cs, OpenOption... options) to write string to file

1
2
3
4
5
6
7
public static void writeFile(String filename, String content) {
try {
Files.writeString(Path.of(filename), content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}

Reference