Java 11 Files Methods Tutorial

beginner
24 min

Java 11 Files Methods Tutorial

Welcome to the Java 11 Files Methods tutorial! In this lesson, we'll learn how to work with files in Java using various methods provided by the java.io package. Let's get started! šŸŽÆ

Introduction

In real-world projects, you often need to read from or write to files. Java provides a comprehensive set of methods to handle files and directories. In this tutorial, we'll cover the most important ones.

File Class

The File class in Java represents a file or directory pathname. You can create a File object to represent an existing or non-existing file or directory.

java
File myFile = new File("example.txt");

šŸ“ Note: To create a new file, you should ensure that the parent directory exists. If it doesn't, you'll need to create it before creating the file.

Checking if a File Exists

To check if a file exists, you can use the exists() method.

java
if (myFile.exists()) { System.out.println("The file exists."); } else { System.out.println("The file does not exist."); }

Creating a File

To create a new file, you can use the createNewFile() method. If the file already exists, it will throw an exception.

java
if (!myFile.exists()) { myFile.createNewFile(); System.out.println("The file has been created."); } else { System.out.println("The file already exists."); }

Deleting a File

To delete a file, use the delete() method.

java
myFile.delete(); System.out.println("The file has been deleted.");

Checking if a Directory Exists

To check if a directory exists, use the isDirectory() method.

java
File myDirectory = new File("exampleDir"); if (myDirectory.isDirectory()) { System.out.println("The directory exists."); } else { System.out.println("The directory does not exist."); }

Creating a Directory

To create a new directory, use the mkdir() method. If the directory already exists, it will throw an exception. To create a directory and its subdirectories, use mkdirs().

java
if (!myDirectory.exists()) { myDirectory.mkdir(); System.out.println("The directory has been created."); } else { System.out.println("The directory already exists."); }

Deleting a Directory

To delete a directory, use the delete() method. However, you cannot delete a non-empty directory directly. You'll need to first delete all files within the directory and then delete the directory itself.

Reading and Writing Files

To read and write files, we'll use the FileReader and FileWriter classes. We'll cover this topic in the next section.


Quiz

Question: What is the purpose of the exists() method in the File class?

A: To create a new file B: To check if a file exists C: To delete a file Correct: B Explanation: The exists() method is used to check if a file or directory exists at the given path.


Stay tuned for the next part, where we'll learn how to read and write files in Java! šŸ’”