Writing to a file in Java is similar to reading from a file, in that you have to be mindful of your exceptions, however, writing is handled by different Classes. But you will find the process very similar.
Setting up the Writer
Instead of using FileReader
, you will want to use FileWriter
.
To use a FileWriter
, you will need to pass it a file name, including any necessary path information to it’s constructor.
FileWriter fw= new FileWriter(fname);
Of course we will want to do this in the try section. The constructor can take a File reference or a string. Additionally, a default character set is used if you don’t define one.
It’s smart to wrap the FilewWriter
in a BufferedWriter
.
String fname = "sample.txt";
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(fname);
bw = new BufferedWriter(fw);
} catch( IOException ioe ) {
// ...
} finally {
// ...
}
Of course, you can always simplify your code using anonymous objects.
bw = new BufferedWriter( new FileWriter(fname) );
Closing the Writer
If you don’t close your writer, you may get a warning about “leaks” that is file handles left open, which can cause memory leaks, and corrupt files.
As with the reader, I like to put this in the finally, to ensure it always executes.
finally {
try {
bw.close();
} catch(IOException ioe) {}
}
As with the reader, I like to do this right away, so it isn’t a forgotten step.
Writing to the File
BufferedWritter has an overloaded method called write, which is typically what we will use to write to a file. We can write a character or a whole string, depending upon what is needed.
The values passed to the write method will keep being appended to the same line until the newline() method is called.
bw.write("Sample Data");
bw.newLine();
If you want to write a non-string piece of data, you will need to convert it to a String.
bw.write(Integer.toString(10));
bw.write(',');
bw.write(Boolean.toString(false));
bw.newLine();
Luckily, all of the primitive data types have methods which would allow you to do that.
For an object, you will also need to use either the toString() method, or some other method would allows you to write it’s data to a string. This is the concept behind the Serializable
method.
Writing to a File in Java was originally found on Access 2 Learn