Skip to main content

Section 8.2 Creating Files

We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject. Listingย 8.2.1 shows the code to create a File object in Java.
Listing 8.2.1.

Note 8.2.2.

myFile is the name of the object within the program, while myfile.txt is the name of the file itself and will be the file name if the operation that creates the file is successful.
Now letโ€™s learn how to make a file in Java. In Python. files can be made using the open() function on a file path that doesnโ€™t exist yet. Similarly, in Java you create a file by using the createNewFile() method on a File object. This method actually does the work of creating a file and saving it in the current working directory, and returns a boolean value of either true or false if the file is successfully created. We can use this methodโ€™s possible return values in tandem with an if/else selection to determine if the file was created. Finally, we encase this code within try/catch blocks. This step is required in the Java code to be compiled. If try/catch blocks using IOException are not included, there will be compilation errors.
Listingย 8.2.3 shows the equivalent code to create a file in Python.
Listing 8.2.3.
Listingย 8.2.4 shows the equivalent code to create a file in Java.
Listing 8.2.4.

Note 8.2.5.

You may have noticed the use of another method from the File class; getName(). This method returns a string containing the name of the file.

Checkpoint 8.2.6.

Construct a short Java program that creates a File object for "myfile.txt" and prints it. Drag the blocks into the correct order on the right.
You have attempted of activities on this page.