How to write to a plain text file in Java
This tutorial shows several ways to write content to a text file in Java.
The techniques used below are pure JDK and don’t use external libraries.
1- BufferedWriter
The most common and efficient way to write content to a file in Java is through using BufferedWriter as the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 | private static void writeFileUsingBufferedWriter() { try(Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("new-file.txt"), "UTF-8"))) { writer.write("First Line"); writer.write("\n"); writer.write("Second Line"); } catch(IOException ex) { ex.printStackTrace(); } } |
This technique is very efficient for writing huge data to a text file.
2- Java nio
Using nio package which is introduced in JDK 7, you can write content to a text file in one line using Files.write() as the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 | private static void writeFileUsingFiles() { List<String> lines = Arrays.asList("First Line", "Second Line"); Path file = Paths.get("new-file.txt"); try { Files.write(file, lines, Charset.forName("UTF-8")); } catch(IOException ex) { ex.printStackTrace(); } } |