Open In App

File Handling in Java

Last Updated : 04 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, file handling means working with files like creating them, reading data, writing data or deleting them. It helps a program save and use information permanently on the computer.

file_handling_in_java
File handling in Java

Why File Handling is Required?

  • To store data permanently instead of keeping it only in memory.
  • To read and write data from/to files for later use.
  • To share data between different programs or systems.
  • To organize and manage large data efficiently.

To support file handling, Java provides the File class in the java.io package.

File Class

File class in Java (from the java.io package) is used to represent the name and path of a file or directory. It provides methods to create, delete, and get information about files and directories.

Example:

Java
// Importing File Class
import java.io.File;

class Geeks 
{
    public static void main(String[] args)
    {
        // File name specified
        File obj = new File("myfile.txt");
        System.out.println("File Created!");
    }
}

Output:

File Created!

In Java, I/O streams are used to perform input and output operations on files. So, let’s first understand what streams are.

I/O Streams in Java

In Java, I/O streams are the fundamental mechanism for handling input and output operations. They provide a uniform way to read data from various sources (files, network, memory) and write data to different destinations.

Java I/O streams are categorized into two main types based on the type of data they handle:

1. Byte Streams

In Java, Byte Streams are used to handle raw binary data such as images, audio files, videos or any non-text file. They work with data in the form of 8-bit bytes.

byte_streams_
Byte Streams

The two main abstract classes for byte streams are:

  • InputStream: for reading data (input)
  • OutputStream: for writing data (output)

Since abstract classes cannot be used directly, we use their implementation classes to perform actual I/O operations.

  • FileInputStream: reads raw bytes from a file.
  • FileOutputStream: writes raw bytes to a file.
  • BufferedInputStream / BufferedOutputStream: use buffering for faster performance.
  • ByteArrayInputStream: reads data from a byte array as if it were an input stream.
  • ByteArrayOutputStream: writes data into a byte array, which grows automatically.

2. Character Streams

In Java, Character Streams are used to handle text data. They work with 16-bit Unicode characters, making them suitable for international text and language support.

character_streams
Character Stream

The two main abstract classes for character streams are:

  • Reader: Base class for all character-based input streams (reading).
  • Writer: Base class for all character-based output streams (writing).

Since abstract classes cannot be used directly, we use their implementation classes to perform actual I/O operations.

  • FileReader: reads characters from a file.
  • FileWriter: writes characters to a file.
  • BufferedReader: reads text efficiently using buffering; also provides readLine() for reading lines.
  • BufferedWriter: writes text efficiently using buffering.
  • StringReader: reads characters from a string.
  • StringWriter: writes characters into a string buffer.

Use Byte Streams when working with binary data (images, audio, video, executable files) and use Character Streams when working with text data (characters, strings, text files).

File Operations

The following are the several operations that can be performed on a file in Java:

  • Create a File
  • Read from a File
  • Write to a File
  • Delete a File

1. Create a File

  • In order to create a file in Java, you can use the createNewFile() method.
  • If the file is successfully created, it will return a Boolean value true and false if the file already exists.

Example:

Java
import java.io.File;
import java.io.IOException;

public class CreateFile
{
    public static void main(String[] args)
    {

        try {
            File Obj = new File("myfile.txt");
            
          	// Creating File
          	if (Obj.createNewFile()) {
                System.out.println("File created: " + Obj.getName());
            }
            else {
                System.out.println("File already exists.");
            }
        }
      
      	// Exception Thrown
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output:

CreateFile
Output

2. Write to a File

We use the FileWriter class along with its write() method in order to write some text to the file.

Example:

Java
import java.io.FileWriter;
import java.io.IOException; 

public class WriteFile 
{
    public static void main(String[] args)
    {
        // Writing Text File       
        try {

            FileWriter Writer = new FileWriter("myfile.txt");

            // Writing File
            Writer.write("Files in Java are seriously good!!");
            Writer.close();
            
            System.out.println("Successfully written.");
        }

        // Exception Thrown
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output:

Writing
Output

3. Read from a File

We will use the Scanner class in order to read contents from a file.

Example:

Java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner; 

public class ReadFile 
{
    public static void main(String[] args)
    {
        // Reading File
        try {
            File Obj = new File("myfile.txt");
            Scanner Reader = new Scanner(Obj);
          
            // Traversing File Data
          	while (Reader.hasNextLine()) {
                String data = Reader.nextLine();
                System.out.println(data);
            }
          
            Reader.close();
        }
        
        // Exception Cases
        catch (FileNotFoundException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output:

ReadFile
Output

4. Delete a File

We use the delete() method in order to delete a file.

Example:

Java
import java.io.File; 

public class DeleteFile 
{
    public static void main(String[] args)
    {
        File Obj = new File("myfile.txt");
        
        // Deleting File
        if (Obj.delete()) {
            System.out.println("The deleted file is : " + Obj.getName());
        }
        else {
            System.out.println(
                "Failed in deleting the file.");
        }
    }
}

Output:

DeleteFile
Output

File Handling
Visit Course explore course icon