Table of contents
1.
Introduction
2.
What Is the File Class in Java?
3.
Why Use File Handling in Java?
3.1.
Common Use Cases for File Handling in Java
3.2.
Why It Matters
4.
Creation 
5.
Fields
6.
Constructors
7.
Methods
7.1.
canExecute()
7.2.
canRead()
7.3.
canWrite()
7.4.
compareTo(File pathname)
7.5.
createNewFile()
7.6.
createTempFile(String prefix, String suffix)
7.7.
delete()
7.8.
equals(Object obj)
7.9.
exists()
7.10.
getAbsolutePath()
7.11.
list()
7.12.
getFreeSpace()
7.13.
getName()
7.14.
getParent()
7.15.
getParentFile() 
7.16.
getPath()
7.17.
setReadOnly()
7.18.
isDirectory()
7.19.
isFile()
7.20.
isHidden()
7.21.
length()
7.22.
listFiles()
7.23.
mkdir()
7.24.
renameTo(File dest)
7.25.
setExecutable(boolean executable)
7.26.
setReadable(boolean readable)
7.27.
setReadable(boolean readable, boolean ownerOnly)
7.28.
setWritable(boolean writable)
7.29.
toString()
7.30.
toURI()
8.
Program
8.1.
Output
9.
Real-World Use Cases of Java File Handling
9.1.
1. Java File Handling in Logging Systems
9.1.1.
Benefits of File-Based Logging
9.1.2.
Example: Writing Logs to a File
9.2.
2. File Class in Configuration File Management
9.2.1.
Why External Configuration Matters
9.2.2.
Example: Reading a .properties File
10.
Frequently Asked Questions
10.1.
What is a class?
10.2.
Define a file.
10.3.
What are exceptions?
10.4.
What are objects?
11.
Conclusion
Last Updated: Jul 7, 2025
Easy

File Class in Java

Author Pankhuri Goel
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The File class represents a file or directory pathname in Java. A simple string is insufficient to name files and directories because they have distinct formats on different platforms. Working with the pathname, deleting and renaming files, establishing new directories, showing the contents of a directory, and identifying various common properties of files and directories are all covered by the File class.

File Class in Java

The File class represents a file or directory pathname in abstract form. There are two types of pathnames: absolute and relative. This class’s getParent() method can be used to find the parent of an abstract pathname.

Instances of the File class are immutable, which means that once generated, a File object’s abstract pathname will never change.

The File class is a part of the java.io package. Another package called java.nio can be used to work with files.

What Is the File Class in Java?

The java.io.File class is part of the Java IO (Input/Output) package. It is used to represent the abstract pathname of a file or directory—not the file's contents. It provides methods to create, delete, inspect, and manipulate files or folders.

This class plays a key role in file management, allowing Java programs to interact with the file system efficiently.

Why Use File Handling in Java?

File handling allows Java applications to interact with the file system to read, write, or manage data stored in files. This is crucial for building real-world applications that require persistent information beyond runtime.

Java provides robust and secure APIs such as File, FileReader, BufferedReader, FileWriter, and Scanner to handle files across different operating systems.

Common Use Cases for File Handling in Java

  • Logging Application Events:
    Save logs to a .log file for debugging or monitoring purposes.
  • Configuration Management:
    Read properties from .properties or .json files to load settings dynamically.
  • Data Storage:
    Store user data (e.g., customer details, report generation, etc.) in .txt or .csv formats.

Why It Matters

  • Ensures data persistence even after the application shuts down.
  • Enables data exchange between systems via files.
  • Java's file APIs are cross-platform, secure, and relatively easy to use.

Creation 

First, we must build a File class object by supplying it with the filename or directory name. Certain operations on the actual file-system object, such as reading, writing, and executing, may be restricted by a file system. Access permissions are a term that refers to all of these constraints.

A File object is formed by supplying a string representing a file name, a String, or another File object as an argument.

Syntax: File fileName = new File(String pathName)

Example: File a = new File("/usr/local/sample");

This specifies an abstract file name for the sample file in the /usr/local directory. This is an absolute abstract file name.

Fields

static String pathSeparator:

It is a system-dependent path-separator character and is rendered as a string for convenience.

static char pathSeparatorChar:

It is a path-separator character that is system-dependent.

static String separator:

It is a string representation of the system-dependent default name-separator character.

static char separatorChar:

It is the default name-separator character that is system-dependent.

Constructors

File(File parent, String child):

Creates a new File instance given a child pathname string and a parent abstract pathname.

File(String pathname)

Converts the specified pathname string to an abstract pathname and creates a new File object.

File(String parent, String child)

Creates a new File instance from a parent pathname string and a child pathname string.

File(URI uri)

Converts the provided file: URI into an abstract pathname to create a new File instance.

Methods

Below mentioned are some of the methods available in the File class.

canExecute()

This function determines whether the application can execute the file specified by this abstract pathname.

Return type: boolean

canRead()

This function determines whether the application can read the file specified by this abstract pathname.

Return type: boolean

canWrite()

This function determines whether the application can edit the file identified by this abstract pathname.

Return type: boolean

compareTo(File pathname)

This method lexicographically compares two abstract pathnames.

Return type: int

createNewFile()

This method atomically creates a new, empty file named by the given abstract pathname.

Return type: boolean

createTempFile(String prefix, String suffix)

In the default temporary-file directory, this method creates an empty file.

Return type: File

delete()

It removes the file or directory that the abstract pathname refers to.

Return type: boolean

equals(Object obj)

In this method, the abstract pathname is compared to the specified object.

Return type: boolean

exists()

This function determines whether the file or directory specified by this abstract pathname exists.

Return type: boolean

getAbsolutePath()

The abstract pathname’s absolute pathname string is returned by this method.

Return type: String

list()

It returns a string array listing the directory’s files and folders.

Return type: String[]

getFreeSpace()

This function returns the number of bytes in the partition that are currently unallocated.

Return type: long

getName()

This function returns the name of the file or directory that this abstract pathname refers to.

Return type: String

getParent()

It returns the pathname string of the abstract pathname’s parent.

Return type: String

getParentFile() 

It returns the abstract pathname of the abstract pathname’s parent.

Return type: File

getPath()

This function converts an abstract pathname to a string pathname.

Return type: String

setReadOnly()

Only read activities are permitted on the specified file or directory.

Return type: boolean

isDirectory()

The file specified by this pathname is checked to see if it is a directory.

Return type: boolean

isFile()

This function determines whether the file represented by the abstract pathname is a regular file.

Return type: boolean

isHidden()

This function determines whether or not the file named by this abstract pathname is hidden.

Return type: boolean

length()

This function returns the length of the file represented by the abstract pathname.

Return type: long

listFiles()

It returns an array of abstract pathnames that denote the directory’s files.

Return type: File[]

mkdir()

In this method, the mentioned abstract pathname is used to create a directory.

Return type: boolean

renameTo(File dest)

The file specified by the abstract pathname is renamed.

Return type: boolean

setExecutable(boolean executable)

It is an easy way to change the owner’s execute authority.

Return type: boolean

setReadable(boolean readable)

It is a quick way to change the owner’s read permission.

Return type: boolean

setReadable(boolean readable, boolean ownerOnly)

It sets the read permission for the owner or everyone.

Return type: boolean

setWritable(boolean writable)

It is a quick way to change the owner’s write authorization.

Return type: boolean

toString()

This method returns the pathname string of the abstract pathname.

Return type: String

toURI()

This method creates a file URI for the given abstract pathname.

Return type: URI

Program

Now let's see a program depicting the working of some of these methods.

import java.io.File;
class fileProperty 
{
	public static void main(String[] args)
	{
		String fname = args[0];
		File f = new File(fname);

		// applying File class methods on File object
		System.out.println("File name: " + f.getName());
		System.out.println("Path: " + f.getPath());
		System.out.println("Absolute path: "+ f.getAbsolutePath());
		System.out.println("Parent: " + f.getParent());
		System.out.println("Exists: " + f.exists());
		
		if (f.exists())
		{
			System.out.println("It is writable: "+ f.canWrite());
			System.out.println("It is readable: " + f.canRead());
			System.out.println("It is a directory: "+ f.isDirectory());
			System.out.println("File size in bytes: "+ f.length());
		}
	}
}

Check out this article - File System Vs DBMS, and Duck Number in Java.

Output

Practice it on online java compiler for better understanding.

Real-World Use Cases of Java File Handling

1. Java File Handling in Logging Systems

In real-world applications, logging is essential for tracking events, errors, and user actions. Java allows developers to write logs to files using the File, FileWriter, and BufferedWriter classes. This ensures persistent logging, which is helpful for debugging, auditing, and monitoring application behavior over time.

Benefits of File-Based Logging

  • Logs are stored permanently, even after a restart.
  • Useful for identifying and fixing bugs.
  • Helps maintain an audit trail of events.

Example: Writing Logs to a File

import java.io.*;

public class LoggerExample {
    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter("app.log", true); // Append mode
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("Application started at " + java.time.LocalTime.now());
            bw.newLine();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program writes a timestamped log entry to app.log. In real-world scenarios, logging libraries like Log4j or SLF4J build on this principle.

2. File Class in Configuration File Management

Java applications often use external configuration files (.properties, .txt, .xml) to store settings like database URLs, API keys, or environment flags. Using the File class to load these files makes the application flexible, easier to maintain, and environment-agnostic.

Why External Configuration Matters

No need to recompile code for setting changes.

Easy to manage environment-specific settings (dev, test, prod).

Improves code modularity and reusability.

Example: Reading a .properties File

import java.io.*;
import java.util.Properties;

public class ConfigReader {
    public static void main(String[] args) {
        try {
            File file = new File("config.properties");
            FileInputStream fis = new FileInputStream(file);
            Properties props = new Properties();
            props.load(fis);

            System.out.println("DB URL: " + props.getProperty("db.url"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program reads key-value pairs from a configuration file. Developers often use this technique for decoupling config from code, making updates simpler and safer.

Frequently Asked Questions

What is a class?

A class is a prototype or blueprint defined by the user and used to create objects. It denotes the collection of properties or methods that all objects of the same type share. It is a logical entity and not a physical one. Fields, methods, constructors, blocks, nested classes, and interfaces can all be found in a Java class.

Define a file.

A file is an abstract path that does not exist in the physical world. The file’s underlying physical storage is only accessed when “used.” An abstract path is produced when a file is created indirectly. A file is one way of storing data according to specified requirements.

What are exceptions?

An exception is an unwanted or unexpected event that occurs during the execution of a programme and disrupts the program’s normal flow of instructions. Exceptions can be detected and handled by the programme. An object is created when a method throws an exception. This object is referred to as an exception object. It includes information regarding the exception, such as the error’s name and description and the program’s state at the time the error occurred.

What are objects?

The instance of a class is known as an object. It represents real-life entities and is a fundamental unit of Object-Oriented Programming. A typical Java application creates a large number of objects, which interact via invoking methods. State, behaviour, and identity are the three attributes of an object.

Conclusion

The File class in Java is a core part of the java.io package and plays a crucial role in file handling. It represents abstract file and directory pathnames and is primarily used to create, delete, and inspect file system elements. Although it does not handle file content directly, it provides essential capabilities for managing file-related operations in a Java program.

This class offers several useful constructors, such as File(String pathname) and File(String parent, String child), allowing flexible instantiation based on file paths.

Live masterclass