Java File Handling

File Handling in Java

April 3rd, 2026
3093
8:00 Minutes

Java file handling gives you the ability to effectively manage files for creating flexible applications. It is important for enabling programs to persist data, interact with external resources and maintain state across sessions. I have created this blog for you to understand what file handling in Java truly means. But would you not like to know more about it? This guide also sheds light on file classes, I/O streams and fundamental file operations in Java with useful examples.

What is file handling in Java?

So, what is Java file handling? Remember that it is all about organizing files by creating, writing, reading or deleting them. It allows a program to save and make use of information on the computer. You can handle the stories stored on the computer’s disk by using Java’s tools, such as streams, readers, etc. All of this can be done while handling errors and spells.

Also Read: How to Install the Java Programming Language?

Why use file handling in Java?

But why does file handling in Java matter? It has an important part in Java, mainly for handling different files along with -

  • It makes sure that data remains stored permanently and does not disappear once the program ends.
  • Data sharing is also performed smoothly across different programs.
  • Information can be reused as it allows reading from and writing to files.
  • Large datasets are managed and organized with ease.

Master Java Programming with Java Training

Boost your coding skills and gain hands-on knowledge in Java.

Explore Now

What is the File Class in Java?

Does File Class in Java sound new to you? I can explain. The Java File class is a part of the java.io package. It serves as a representation of a file or directory’s name and location. It gives you ways to make, delete and get data about files or directories as well. Here is an example -

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

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

        File obj = new File("myfile.txt");

        try {
            if (obj.createNewFile()) {
                System.out.println("File created successfully!");
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

File Created!

Also Explore: Java 21 Features

Modern File Handling with Java NIO

Modern Java applications commonly use the java.nio.file package for file handling because it provides better performance, cleaner syntax and improved scalability compared to traditional I/O classes. Introduced in Java 7, Java NIO simplifies many file operations using classes like Path, Paths and Files.

Developers prefer Java NIO for handling large files, performing non-blocking operations and writing cleaner code in enterprise applications.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

public class NIOExample {

    public static void main(String[] args) {

        Path path = Path.of("example.txt");

        try {

            Files.writeString(path, "Hello from Java NIO!");

            String content = Files.readString(path);

            System.out.println(content);

        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}

I/O Streams in Java

Let me introduce you to I/O streams in Java. They are an important structure for handling input and output operations. They give a unified approach to read data from different sources like network, memory and files along with writing output to different destinations.

Byte Streams

Byte streams in Java handle raw binary data like audio, video, non-text files or images. They process data as sequences of 8-bit bytes. The two primary abstract classes that define Java’s byte stream architecture are InputStream for reading data and OutputStream for writing it. Abstract classes cannot be instantiated directly; this is why their implementation classes are used to perform actual I/O operations -

  • FileInputStream - It reads unprocessed bytes directly from a file.
  • FileOutputStream - It writes unprocessed bytes directly from a file.
  • BufferedInputStream/BufferedOutputStream - It uses buffering for boosting overall performance.
  • ByteArrayInputStream - It reads data from a byte like it were an input stream.
  • ByteArrayOutputStream - This one writes data into a byte array which grows naturally.

Character Streams

Character streams in Java are designed for handling text data. It is ideal for international text and language support as it works with 16-bit Unicode characters. They are best for working with text data like strings, characters and text files. There are two key abstract classes for character streams: Reader and Writer. Abstract classes cannot be instantiated directly, this is why their implementation classes are used to perform actual I/O operations -

  • FileReader - It reads characters from a file.
  • FileWriter - It writes characters to a file.
  • StringReader - It reads characters from a string in memory.
  • StringWriter - It writes characters into a string buffer.
  • BufferedReader - It reads text efficiently by buffering characters and supports line-by-line reading using readLine().
  • BufferedWriter - It writes text efficiently by buffering character output before writing to a file.

Character Encoding in Java

Character encoding is important while reading or writing text files in Java. Modern applications commonly use UTF-8 encoding to properly support international characters and multilingual text data.

Developers can specify encodings explicitly using classes like InputStreamReader, OutputStreamWriter or Files.writeString() with StandardCharsets.UTF_8.

Read Also:  How to Learn Java from Scratch

File Operations

Java allows a number of important file operations like creating, reading, writing and deleting files. Let’s take a look at each operation one by one-

File Operations

Create a File

One can create a file in Java by using the createNewFile() method. This method returns true when a new file is successfully created and returns false if a file with the specified name already exists. Here is an example to help you out -

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

public class CreateFileExample {

    public static void main(String[] args) {

        File file = new File("example.txt");

        try {

            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }

        } catch (IOException e) {

            System.out.println("An error occurred:");
            e.printStackTrace();
        }
    }
}

Output

  • If the file does not exist -
File created
  • If the file does exist -
File already exists

Write to a file

We can send text into a file through Java’s FileWriter class and its write() method. Here is an example -

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class WriteToFileExample {

    public static void main(String[] args) {

        // Specify the file name
        String fileName = "output.txt";
        String content = "Hello, Java FileWriter!";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {

            writer.write(content);

            System.out.println("Text successfully written to " + fileName);

        } catch (IOException e) {

            System.err.println("An error occurred while writing to the file: " + e.getMessage());
        }
    }
}

Output

Text successfully written to output.txt

The examples above use try-with-resources, a modern Java feature introduced in Java 7. It automatically closes file resources after use, helping developers avoid memory leaks and resource management issues.

Read from a file

We can read contents from a file through the Scanner class. Here is an example -

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

public class ReadFileExample {

    public static void main(String[] args) {

        // Specify the file to be read
        File file = new File("sample.txt");

        try (Scanner scanner = new Scanner(file)) {

            // Read and print each line from the file
            while (scanner.hasNextLine()) {

                String line = scanner.nextLine();
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {

            System.err.println("File not found: " + e.getMessage());
        }
    }
}

Output

This is what the expected output would look like -

Hello, Java!
Welcome to file handling.
Enjoy coding!

Although Scanner is beginner-friendly, modern Java applications often use BufferedReader or the Files class from Java NIO for better performance and cleaner code when working with large files.

Delete a file

We can get rid of a file by using the delete() method.

import java.io.File;

public class DeleteFileExample {

    public static void main(String[] args) {

        // Specify the file to be deleted
        File file = new File("sample.txt");

        // Attempt to delete the file
        if (file.delete()) {

            System.out.println("File deleted successfully: " + file.getName());

        } else {

            System.out.println("Failed to delete the file: " + file.getName());
        }
    }
}

Output

  • If the file sample.txt exists and is successfully deleted.
File deleted successfully: sample.txt
  • If the file sample.txt does not exist and cannot be deleted.
Failed to delete the file: sample.txt

Read Also:  60+ Java Interview Questions and Answers

Java IO vs Java NIO

Feature Java IO Java NIO
Approach Stream-based Buffer-based
Performance Suitable for smaller tasks Better for large-scale applications
Blocking Operations Blocking Supports non-blocking operations
Modern Usage Used for basic and legacy applications Preferred in modern Java development

Conclusion

I hope this guide helped you understand the core concepts of file handling in Java. Modern Java applications use both traditional I/O classes and the Java NIO package for efficient file operations, better scalability and cleaner code structure. By learning file creation, reading, writing and deletion along with modern APIs like Files and Path, developers can build reliable applications that manage data efficiently.

I hope this guide helped you in exploring the important aspects of file handling in Java. The purpose of this blog is to equip readers with a strong grasp of these operations for building applications that require data persistence. Java file handling allows developers to perform file operations with ease through using powerful I/O libraries like BufferedReader, BufferedWriter, and more.

FAQs

Q1. What are the benefits of using Java New I/O over traditional I/O?

Java NIO gives you buffer-oriented data handling, non-blocking I/O and selectors for flexible applications. It is great for high performance and concurrent file operations as compared to traditional I/O.

Q2. How can developers ensure thread-safe file operations in Java?

Developers must ensure safety by using synchronization mechanisms like ReentrantLock and synchronized blocks as Java’s I/O classes are not inherently thread safe.

Q3. What are the best practices for handling large files in Java?

The best practices include using BufferReader or BufferWriter for reading and writing data in chunks for large files. Another best practice is to avoid loading the entire file into memory to prevent OutOfMemoryError.

Q4. What is the purpose of file handling in Java?

File handling in Java is used to create, read, write and manage files on a system. It allows programs to store data permanently instead of losing it when the program stops running.

Q5. Which API is best for handling large files in Java?

Modern Java applications commonly use Java NIO classes like Files, Path and BufferedReader for handling large files efficiently. These APIs improve performance and reduce memory usage compared to older approaches.

About the Author
Author Nehal Sharma
About the Author

Nehal Sharma is a skilled Data Analyst with expertise in Java, mobile development, and data analytics. She transforms complex data into actionable insights and has experience in business intelligence, data science, and Salesforce. She also simplifies technical concepts into clear, engaging content for learners and professionals.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.