Writing to Text Files
If we want our program to print information to a text file, we first need to open a connection to that file.:
PrintWriter pw = new PrintWriter((filename);Here, filename is the name of the text file we want
to print to. If this file doesn’t exist, it will be created in the same directory as your code. If it
does exist, everything in the file will be overwritten.
Now we can write to the file. Here’s how to write a single line of text (and advance to the next line):
pw.println(stuff);Here, stuff is the String, int, char, or double that you want to write to the file. This
function works exactly like System.out.println. To print a line without advancing to the
next line, do:
pw.print(stuff);When you’re done writing to the file, close your connection:
pw.close();Closing the file is especially important after you’ve written information to it. When you write to a file, the information doesn’t get immediately written. Instead, it gets stored in a temporary buffer. When the buffer gets full, the entire buffer is written to the file at once. When you close the file, it writes whatever is in the buffer to the file. If you forget to close it, then whatever information was still in the buffer will not get written to the file.
Example
These arrays will hold people’s names and ages, respectively:
String[] names;
int[] ages;Suppose those arrays have been initialized and filled with data. Suppose also that they are the
same length, and that names[i] is a person’s name and ages[i] is the same person’s age. We
want to print:
name: ageFor each person to the file info.txt. Here’s how:
//open a connection to the file
PrintWriter pw = new PrintWriter("info.txt");
//print name: age for each person
for (int i = 0; i < names.length; i++)
{
pw.println(names[i] + ": " + ages[i]);
}
//close the file
pw.close();Note: we could also use the printf command to print formatted values to an output file, just like we use System.out.printf to print formatted information to the console.