Java – Write to File (source 1)
Java – Write to File (source 2)
The simplest way to write to files in Java is with FileWriter.
Example:
import java.io.File; import java.io.FileWriter; import java.io.IOException; public static void writeFile() throws IOException { File f = new File("output.txt"); FileWriter fr; fr = new FileWriter(f); fr.write("Line 1 Data\n"); fr.write("Line 2 Data"); fr.close(); }
If all you need to do is start from a blank file and write multiple lines, FileWriter is a good choice.
The example above include “\n” to create a line break.
The method has “throws Exception” to allow for the possibility that Java won’t be able to create or access the “output.txt” file. An exception is like an error. Sometimes Java forces you to create a backup plan when an exception is possible. This can be done by throwing an exception (like above) or by using try/catch (see the read file section for example)
If you need fancier file writing, like writing into the middle of a file, read the links above to get some ideas.
If you run code like this and it creates a blank file, you can use a BufferedWriter object. This will hopefully handle memory management and timing issues within the operating system and fix the problem.
BufferedWriter takes a FileWriter as its input parameter as shown in the example below.
import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public static void writeFile() throws IOException { File f = new File("output.txt"); FileWriter fr; fr = new FileWriter(f); BufferedWriter br; br = new BufferedWriter(fr); br.write("Line 1 Data\n"); br.write("Line 2 Data"); br.close(); }
Notice that the example has br.write(“…”) instead of fr.write(“…”).