This write-up presents a profound understanding of java file handling methods and in this regard, we are going to cover the following aspects of file handling:
- File Handling Methods
- How to Create a File
- How to Write data to a File
- How to Delete a File
- How to Read Data from a file
- How to get File Name and Path
- How to Check the Existence of a File
- How to Check if the File is Readable and Writable or Not
- How to find the File size in Java
So, let’s get started!
File Handling Methods
Java provides a wide range of file handling methods that can be used to perform various functionalities such as createNewFile() to create the file. The list of some frequently used file handling methods is provided in the below-given table:
Method Name | Description |
---|---|
createNewFile() | Boolean type method used to create an empty file. |
mkdir() | Boolean type method that creates a directory. |
delete() | Boolean type method that deletes a file. |
getName() | String type method used to get the file name. |
getAbsolutePath() | String type method used to get the file path. |
list() | String type method used to get the array of files within a directory. |
canRead() | Boolean type method that checks whether the file is readable or not. |
canWrite() | Boolean type method that checks whether the file is writable or not. |
exists() | Boolean type method that checks whether the specified file exists. |
length() | Long type method used to get the size of file in Bytes. |
write() | Used to write data to a file |
nextLine() | Used to read the content of any specific file |
In this write-up, we will discuss some commonly used file handling methods along with examples.
How to Create a File in Java using createNewFile() method
The File class in java provides a very useful method createNewFile() that can be used to create an empty file. On successful creation of the file, we will get a boolean value true, else we will get a false value.
Example
Let’s consider the below-given snippet for the profound understanding of file creation in java.
import java.io.File;
import java.io.IOException;
public class FileHandlingExample {
public static void main(String[] args) {
try {
File fileObj = new File("C:FileHandlingExample.txt");
if (fileObj.createNewFile()) {
System.out.println("File created: " + fileObj.getName());
} else {
System.out.println("File Exists Already");
}
} catch (IOException excep) {
System.out.println("Error");
excep.printStackTrace();
}
}
}
In the above-given snippet we created the object of the File class and within parentheses we specified the file name and path. Afterward, there are three possibilities: file created successfully, file already exists or an Error occurs so for that we utilized the concept of try-catch to handle the exceptions:
From the above snippet, it is clear that the createNewFile() method of the File class is working properly as it succeeds in creating a file.
How to Write Data to a File
Java provides a built-in class FileWriter that can be used to write data to any file and to do so, the FileWriter class provides a write() method. While working with the FileWriter class we have to utilize the close() method to close the file.
Example
Let’s consider the below code snippet that provides a detailed understanding of how to write data to a file:
import java.io.File;
import java.io.IOException;
public class FileHandlingExample {
public static void main(String[] args) {
try {
File fileObj = new File("C:FileHandlingExample.txt");
if (fileObj.createNewFile()) {
System.out.println("File created: " + fileObj.getName());
} else {
System.out.println("File Exists Already");
}
} catch (IOException excep) {
System.out.println("Error");
excep.printStackTrace();
}
}
}
In the above code snippet, we created an object of the FileWriter class, and within the parenthesis, we specified the file name to whom we want to write the data. Next, we utilize the write() method of the same class to write the data to the file and then close the file using the close() method. Finally, we handled the exceptions in the catch block using the IOException class.
The output validates that the write() method succeeds in writing the data to a file.
How to Read Data from a file in Java Using nextLine() method of Scanner Class
We can utilize some built-in methods of the Scanner class to read the content of any specific file.
Example
In the below code snippet, we create the object of the Scanner class and specify the name and path of the file from where we want to read the data. Moreover, we utilize the try-catch statements to handle the exceptions.
public static void main(String[] args) {
try {
File fileObj = new File("C:\\Users\\DELL\\Desktop\\file1.txt");
Scanner scanObj = new Scanner(fileObj);
while (scanObj.hasNextLine()) {
String data = scanObj.nextLine();
System.out.println(data);
}
scanObj.close();
} catch (FileNotFoundException excep) {
System.out.println("Error");
excep.printStackTrace();
}
}
}
In this example, we utilize the hasNextLine() method within the loop that will check whether a line left if yes then it will return true and our loop will continue iterating until it gets a false value. Next, we utilize the nextLine() method to get a String, and finally, we print the String:
The above snippet verifies that the Scanner class succeeds to read the data of “file1.txt”.
How to Delete a File using delete() method
The File class provides another handy method known as delete() method that can be used to delete a specific file.
Example
The below code snippet provides a detailed understanding of how to delete a file using delete() method:
The complete code and respective output is provided in the below-given snippet:
The above output verifies that the delete() method successfully deletes the specified file.
Implementation of Multiple File Methods
The java file class offers numerous methods that can be utilized in order to get the detailed information of the file.
How to check a file exists in Java using exists() method?
In this example we utilize the exists() method to test the existance of the specified file. If the file exists then show the detailed information about that file such as file name, path, size of the file, and either it’s readable and writable, or not.
if (fileObj.exists()) {
System.out.println("File_Name: " + fileObj.getName());
System.out.println("File_Path: " + fileObj.getAbsolutePath());
System.out.println("File_Readable " + fileObj.canRead());
System.out.println("File_Writeable: " + fileObj.canWrite());
System.out.println("File_Size in bytes " + fileObj.length());
}
else {
System.out.println("File not exist");
}
The below-snippet describes the working of the above code snippet and provides the respective output:
The output verifies the existence of a file as well as the working of each individual file method.
Conclusion
Java provides multiple methods for file handling such as createNewFile(), delete(), write() and nextLine() methods are used for file creation, deletion, writing, and reading the data from a file respectively. Similarly canRead(), canWrite(), getName(), getPath(), and size() are widely used file methods to get the file information like file readability, file writable, file name, path, and size respectively. This write-up presents a detailed overview of the file handling methods and for the clarity of concepts this article considers some major file methods and implement them practically.