Section 8.4 Writing to Files
The
createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however,
createNewFile() does not write anything to files it creates. In fact, if you use
createNewFile() to create a
.txt file and then open the file, the file will be blank.
Let us create the framework for a class that will write to a file. Letβs call this class
WriteFile:
Next, we will create a
FileWriter object. Letβs call it
myWriter:
FileWriter myWriter = new FileWriter("myfile.txt");
In this next step, we will use the
write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The
write() method takes most standard data types:
myWriter.write("File successfully updated!");
myWriter.close();
Next, we will again add the required try/catch blocks utilizing the
IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:
And the equivalent Java code:
And thatβs it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:
Files in a specific directory can be written to using the same technique as the last section in which file paths are specified, with two back slashes used in Windows environments.
Speaking of overwriting data, what if we want to append text to the end of any text already in
myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:
FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
Now, when we use
write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument:
Then if we run the program twice, the contents of
myfile.txt would be:
File successfully updated!File successfully updated!
This doesnβt look very good! If we want each additional write to appear on a new line? The first solution may be to use the
\n newline character:
myWriter.write("File successfully updated!\n"); // Added newline character
myWriter.close();
The System.lineseseparator() method is a better solution. This method returns the systemβs default line separator, which is platform-dependent. For example, on Windows, it returns
\n, while on Linux and macOS, it returns
\n. Using this method ensures that your code works correctly across different operating systems:
myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character
myWriter.close();
Running it twice will result in the following contents in myfile.txt:
File successfully updated!
File successfully updated!
You have attempted
of
activities on this page.