How does filing work in Java?

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 local file systemthe operating systems.

The built-in File class from the java.io package is an abstract representation of file or directory pathname. The pathname can be either absolute or relative.

File class operations

There are multiple operations we can perform through the File class in Java, as listed below.

  • Create a file or directory.
  • Rename and delete files or directories.
  • List directories.
  • Write/append to a file.
  • Read from a file.

Java file methods

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.

Code

Create a file

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 error
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
try { //try-catch block
File 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
}
}
}

Write to a file

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 error
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try { //try-catch block
FileWriter 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
}
}
}