Java file handling with example programs

File handling in Java is a fundamental aspect of programming that involves reading and writing to files. It is essential for any Java developer who wishes to create programs that can store and retrieve data from disk files. Java provides a comprehensive set of APIs for handling file operations efficiently, regardless of the type of file involved.

This article will cover the fundamentals of Java file management and provide example programs to help you get started.

The act of creating, reading, writing, and manipulating files is referred to as file handling in Java. Classes and interfaces for Java file input and output operations are provided by the "java.io" package.

Java classes for file management

Here are some of the most commonly used Java classes for file management. I listed and briefly described the most commonly used methods, as well as examples of all of the listed classes.

File class in Java

A file or directory path on the file system is represented in Java by the File class. It offers ways to create, remove, and modify files and directories.

Following is a list of the most commonly used methods of the "File" class in Java:

Java File class: File() constructor

Since the "File()" method has the same name as the class, we can call it a constructor, which is used to create a new "File" object with the specified pathname. As an example:

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

Java File class: createNewFile() method

The createNewFile() method creates a new empty file at the path specified by the File object. As an example:

File file = new File("codescracker.txt");
boolean created = file.createNewFile();

If you are looking for the complete Java example program that creates a new file entered by the user, then here it is:

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

public class CreateFileExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the name of the file to be created: ");
        String fileName = scanner.nextLine();

        // Create a new file object
        File file = new File(fileName);

        try {
            // Try to create the file
            boolean success = file.createNewFile();
            if (success) {
                System.out.println("File created successfully.");
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred while creating the file: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }
}

If we execute this Java program, then we will get the following output:

java file handling example

To create a file, type the name, say xyz.txt, and hit the ENTER key to get the following output:

java file handling program

If you look in the current directory (the directory where the Java source code is saved), you will see the file "xyz.txt."

This Java program prompts the user for the name of the file to be created, creates a new File object with the entered file name, and then attempts to create the file using the File class's createNewFile() method. The createNewFile() method returns a boolean value indicating file creation success. "File created successfully" appears if the file is created. Otherwise, the program displays "File already exists."

In case an exception occurs while creating the file, such as the file path not being accessible, the createNewFile() method throws an IOException. The program catches this exception using a catch block and displays an error message indicating the cause of the exception. Finally, the program closes the Scanner object to release any resources associated with it using the finally block.

Java File class: delete() method

The delete() method deletes the file or directory specified by the "File" class object. As an example:

File file = new File("codescracker.txt");
boolean deleted = file.delete();

The exists() method returns true if the file or directory specified by the "File" class object exists. As an example:

File file = new File("codescracker.txt");
boolean exists = file.exists();

Java File class: getName() method

The getName() method returns the name of the file or directory specified by the "File" class object. Consider the following code fragment as an example:

File file = new File("codescracker.txt");
String name = file.getName();

Java File class: listFiles() method

The listFiles() method of the "File" class object returns an array of "File" objects, each of which represents a file in the directory that was originally specified. Consider the following code fragment as an example:

File directory = new File("mydir");
File[] files = directory.listFiles();

Java File class: mkdir() method

When we need to create a new directory at the path that the "File" class object specifies, we use the mkdir() method. As an example:

File directory = new File("mydir");
boolean created = directory.mkdir();

Java File class: renameTo() method

The renameTo() method is used when we need to rename a file or directory specified by the "File" class object. As an example:

File oldFile = new File("xyz.txt");
File newFile = new File("abc.txt");
boolean renamed = oldFile.renameTo(newFile);

Java File class: length() method

When we need to get the size of a file specified by the "File" class object, we use the length() method. It gives you the size in bytes. As an illustration:

File file = new File("codescracker.txt");
long fileSize = file.length();

FileReader class in Java

The FileReader class offers multiple methods to read data from a file. This class is defined in the "java.io" package. Following is a list of the most common methods:

Java FileReader class: FileReader() constructor

Since the "FileReader()" method is the same name as the class, we can call it a constructor, which is used to create a new FileReader to read a file. As an example:

File file = new File("codescracker.txt");
FileReader fileReader = new FileReader(file);

If you're looking for a complete Java example program that reads a file that the user has entered, here it is:

Java Code
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileReaderExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the name of the file to be read: ");
        String fileName = scanner.nextLine();

        File file = new File(fileName);

        try {
            FileReader fileReader = new FileReader(file);

            System.out.println("\nThe content of the file is:");
            int character;
            while ((character = fileReader.read()) != -1) {
                System.out.print((char) character);
            }

            fileReader.close();
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }
}
Output
Enter the name of the file to be read: myfile.txt

The content of the file is:
Hey,
what's up?
I'm Edwin, from Houston.

Java FileReader class: close() method

This method closes the FileReader and releases any associated system resources. As an example:

fileReader.close();

FileWriter class in Java

In Java, the FileWriter class is part of the java.io package and is used to write data to files either character by character or using an array of characters. It is used to write data in a character stream and extends the java.io.OutputStreamWriter class.

Following is a list of the most commonly used methods provided by the "FileWriter" class in Java:

Java FileWriter class: FileWriter() constructor

Because this method has the same name as its class, we can call it a constructor, which is used to create a new FileWriter given the file to be written. As an example:

FileWriter fileWriter = new FileWriter("codescracker.txt");

Java FileWriter class: write() method

The write() method is used when we need to write data into the file. As an example, consider the following code fragment:

FileWriter fileWriter = new FileWriter("codescracker.txt");
fileWriter.write("Hello, World!");

If you're looking for a complete Java example program that writes data into a file where both the file and the data are entered by the user at run-time of the program, here it is:

Java Code
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FileWriterExample {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the name of the file: ");
        String fileName = scanner.nextLine();

        System.out.print("Enter the content to be written to the file: ");
        String content = scanner.nextLine();

        try {
            FileWriter fileWriter = new FileWriter(fileName);
            fileWriter.write(content);
            fileWriter.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing to the file.");
            e.printStackTrace();
        }
    }
}
Output
Enter the name of the file: codescracker.txt
Enter the content to be written to the file: Hello there! Java is fun!
Successfully wrote to the file.

Java FileWriter class: append() method

The append() method is used when we need to append the content or data into the file instead of overwriting it. As an example:

FileWriter fileWriter = new FileWriter("codescracker.txt", true);
fileWriter.append("content to append");

We use true as the second argument to the "FileWriter()" constructor to open the appending mode.

Java FileWriter class: close() method

The close() method is used when we need to close the FileWriter to release any system resources associated with it. As an example:

fileWriter.close();

BufferedReader class in Java

In Java, the "BufferedReader" class is used to read character streams, such as a text file line by line. It is more efficient than reading directly from a "Reader" object because it reads characters from a stream and stores them in an internal buffer, allowing for more efficient stream reading.

The following is a list of the most commonly used methods provided by the "BufferedReader" class in Java:

Java BufferedReader class: readLine() method

This method returns a String containing a line of text from the input stream. If the end of the stream has been reached, it returns null. For example:

Java Code
import java.io.*;
import java.util.Scanner;

public class ReadLineExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the file name: ");
        String fileName = scanner.nextLine();

        try {
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line = null;

            System.out.println("\nThe file contains:");
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output
Enter the file name: 
myfile.txt

The file contains:
Hey,
what's up?
I'm Edwin, from Houston.

Java BufferedReader class: read() method

This method reads and returns a single character from the input stream. Returns -1 if the end of the stream has been reached. As an example:

Java Code
import java.io.*;

public class BufferedReaderExample {
    public static void main(String[] args) {
        try {
            FileReader fileReader = new FileReader("myfile.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            int ch;

            while ((ch = bufferedReader.read()) != -1) {
                System.out.print((char)ch);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Output
Hey,
what's up?
I'm Edwin, from Houston.

Java BufferedReader class: close() method

And finally, the close() method is used to close the input stream to release any system resources associated with it. As an example:

bufferedReader.close();

BufferedWriter class in Java

Java's BufferedWriter class makes it simple to write character data to a file or any other kind of output stream by internally buffering the data. It is used to increase the efficiency of I/O operations and is an implementation of the "Writer" class. By using a buffer, fewer I/O operations are required as the data is written to the output stream in larger chunks.

Following is a list of the most commonly used methods of the "BufferedWriter" class in Java:

Java BufferedWriter class: BufferedWriter() constructor

The BufferedWriter() constructor returns a new buffered writer instance that writes to the "Writer" instance specified. As an example:

FileWriter writer = new FileWriter("codescracker.txt");
BufferedWriter buffer = new BufferedWriter(writer);

Java BufferedWriter class: write() method

When we need to send some text to the output stream, we call write(). As an illustration:

FileWriter writer = new FileWriter("codescracker.txt");
BufferedWriter buffer = new BufferedWriter(writer);

buffer.write("I'm Edwin.");

The following is a complete Java example program demonstrating how to write data or content into a file using the "write()" method of the "BufferedWriter" class. I designed this program so that the user can enter both the file name and the content to write at the program's run-time:

Java Code
import java.io.*;

public class WriteToFileExample {
    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter the file name: ");
        String fileName = null;
        try {
            fileName = reader.readLine();
        } catch (IOException e) {
            System.out.println("Error reading file name");
            return;
        }

        System.out.print("Enter the content to write: ");
        String content = null;
        try {
            content = reader.readLine();
        } catch (IOException e) {
            System.out.println("Error reading content");
            return;
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("Content written to file successfully.");
        } catch (IOException e) {
            System.out.println("Error writing to file");
            e.printStackTrace();
        }
    }
}
Output
Enter the file name: codescracker.txt
Enter the content to write: I'm Edwin.
Content written to file successfully.

Java BufferedWriter class: newLine() method

To insert a line break into the output stream, we use the newLine() method. As an illustration:

buffer.newLine();

Java BufferedWriter class: close() method

And to close the output stream, use the close() method. For example:

buffer.close();

"InputStream", "OutputStream", "InputStreamReader", "OutputStreamWriter", "DataInputStream", "DataOutputStream" and others may be used occasionally. The class and methods above allow you to perform all file management tasks, including reading, writing, appending, and closing.

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!