Skip to main content

Java For Python Programmers Edition 2

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:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteFile {
    public static void main(String[] args) {
     
    }
}
Next, we will create a FileWriter object. Let’s call it myWriter. The equivalent Python code to this operation is:
with open("myfile.txt", "w") as myWriter:
The Java code to create a FileWriter object is:
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. First, how this step is completed with Python:
my_writer.write("File successfully updated!")
And the Java equivalent. This is almost completely identical except for the second line, which is very important!
myWriter.write("File successfully updated!");
myWriter.close();

Note 8.4.1.

The close() method is being used after writing to the file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided!
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:
try:
    with open("myfile.txt", "w") as my_writer:
        my_writer.write("File successfully updated!")
    print("File successfully written to.")
except OSError as e:
    print("An error occurred.")
    import traceback
    traceback.print_exc()
And the equivalent Java code:
try {
    FileWriter myWriter = new FileWriter("myfile.txt");
    myWriter.write("File successfully updated!");
    myWriter.close();
    System.out.println("File successfully written to.");
} catch (IOException e) {
    System.out.println("An error occurred.");
    e.printStackTrace();
}
And that’s it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:
Data: myfile.txt
The completed Java code:
Data: myfile.txt

Note 8.4.2.

If a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever.
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 tSext in the document. If we were to update our code to include the boolean argument:
Data: myfile
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? A simple solution is to use the \n newline character:
myWriter.write("File successfully updated!\n"); // Added newline character 
myWriter.close();
Running the code with the newline character twice will result in the following contents in myfile.txt:
File successfully updated!
File successfully updated!
You have attempted of activities on this page.