Hi everyone, welcome back. In this tutorial, we will be going over Files in Java. Primarily about how to retrieve information about files. If you are interested in seeing how to read and write to files, refer to this article. Java Files are useful to handle functions regarding file systems such as accessing them. We will go over how to retrieve file information such as it’s path and size. With this introduction out of the way, let’s get into it.
Creating a File
Let’s start by creating a File object in Java. Before we can create the File, we need to make sure we have our needed imports, which are going to be within the java.io package:
import java.io.*;
Now, we can successfully create our File:
try {
File myFile = new File("file.txt");
if (!myFile.exists()) {
myFile.createNewFile();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
First off, we want to wrap everything inside of the try-catch statement in case an unexpected error occurs with opening/creating the file. Then we are creating our File object named “file.txt” and if this file does not exist within your file directory, it will be created. After successfully running this code, a new file(assuming you don’t already have this file) named “file.txt” should appear after refreshing your file directory.
Getting the Name of the File
Let’s see how we can retrieve the file name of our File object. We can do this by using the getName() function. Let’s see an example:
try {
File myFile = new File("file.txt");
if (myFile.exists()) {
System.out.println(myFile.getName());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}Output:
file.txt
In the example above, we can see that we used the getName() function to retrieve the file name. We can check the name in the output.
Absolute Path of the File
Let’s see how we can retrieve the absolute path of our File object. We can do this by using the getAbsolutePath() function. Let’s see an example: