Member-only story
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…