File handling is necessary to perform various tasks to file such as creating files, writing, reading, and more. The File library helps create and locate files in the
The built-in
File
class from thejava.io
package is an abstract representation of file or directory pathname. The pathname can be either absolute or relative.
File
class operationsThere are multiple operations we can perform through the File
class in Java, as listed below.
Here are some useful functions or methods from the File
class. These are used for file handling from any level.
Type | Method | Description |
---|---|---|
Boolean | canWrite() |
Check for access to writing in file. |
Boolean | createNewFile() |
Create a new file in the specified directory. |
Boolean | canRead() |
Check whether or not the specified file is readable. |
Boolean | mkdir() |
Make/Create a new directory. |
String | getName() |
Returns the name of file specified. |
String | getAbsolutePath() |
Returns the current path of the file. |
String[] | list() |
Array of strings that have the file name at each index. |
Boolean | delete() |
Deletes a specified file from current directory. |
Boolean | exists() |
Returns true if the specified file exits, or false if it does not. |
Long | length() |
Returns the size of file in bytes. |
The code below helps create a new file in the current program directory named myFile.txt
.
// Creating a file// Handling exception for any type of errorimport java.io.File;import java.io.IOException;public class CreateFile {public static void main(String[] args) {try { //try-catch blockFile file = new File("myFile.txt");if (file.createNewFile()) {System.out.println("File named successfully created: " + file.getName());} else {System.out.println("Oops File already exists.");}} catch (IOException e) {System.out.println("An error occurred.");e.printStackTrace(); // exception handler}}}
The following code helps to write a file (if it exists) into the current program directory named filename.txt
. Otherwise, a new file with the same name will be created first.
// Writing to a file// If filename.txt not available in the current dir it will create itself// Handling exception for any type of errorimport java.io.FileWriter;import java.io.IOException;public class WriteToFile {public static void main(String[] args) {try { //try-catch blockFileWriter myObj = new FileWriter("filename.txt");myObj.write("Welcome to Educative, Level up your coding skills. No more passive learning.");myObj.close();System.out.println("Operation Successful");} catch (IOException e) {System.out.println("Ooops! An error occurred.");e.printStackTrace(); // exception handler}}}