Member-only story
Hi everyone, welcome back. In this tutorial, we will be going over Files in Java. Java Files are useful to handle functions regarding file systems such as accessing them. We will go over how to create a file, read from a file, and how to write to a file with Java. 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.