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 | public static void writeFile(String filename, String content) { |
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 | try { |
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 | public static void appendFile(String filename, String content) { |
Append to file using Files.newBufferedWriter
method
1 | public static void appendFile(String filename, String content) { |
PrintWriter
If you need to print formatted text, then use java.io.PrintWriter
1 | public static void writeFile(String filename, String content) { |
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 | public static void writeFile(String filename, String content) { |
use writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)
to write string to file
1 | public static void writeFile(String filename, String content) { |