Skip to main content

Java For Python Programmers Edition 2

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.
Data: myfile.txt

Note 8.2.1.

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 that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method’s possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory.
First, lets look at the equivalent Python code:
Now, let’s look at Java code that accomplishes the same task:

Note 8.2.2.

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.
You have attempted of activities on this page.