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! šÆ
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.
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.
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.
To check if a file exists, you can use the exists() method.
if (myFile.exists()) {
System.out.println("The file exists.");
} else {
System.out.println("The file does not exist.");
}To create a new file, you can use the createNewFile() method. If the file already exists, it will throw an exception.
if (!myFile.exists()) {
myFile.createNewFile();
System.out.println("The file has been created.");
} else {
System.out.println("The file already exists.");
}To delete a file, use the delete() method.
myFile.delete();
System.out.println("The file has been deleted.");To check if a directory exists, use the isDirectory() method.
File myDirectory = new File("exampleDir");
if (myDirectory.isDirectory()) {
System.out.println("The directory exists.");
} else {
System.out.println("The directory does not exist.");
}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().
if (!myDirectory.exists()) {
myDirectory.mkdir();
System.out.println("The directory has been created.");
} else {
System.out.println("The directory already exists.");
}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.
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! š”