Java File Handling: Mastering File Operations in Java

Learn the essentials of Java file handling with the powerful File class from the java.io package. This guide covers the fundamental operations for creating, reading, writing, and deleting files in Java applications. Discover how effective file handling enhances your application's functionality and user experience.



Java File Handling

File handling is an important part of any application. Java provides the File class in the java.io package to work with files.

Syntax

import java.io.File;  // Import the File class

File myObj = new File("filename.txt"); // Specify the filename
Output

File Class Methods

Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory