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...