File Handling in Java Complete Guide

File Handling in Java Complete Guide

12 Sep 2024
Beginner
613 Views
16 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

File Handling in Java

File handling in Java is an important programming aspect because it allows programs to interface with files to read, write, and manipulate data. Java's I/O (Input/Output) module includes a complete collection of file management utilities. Understanding Java's file-handling capabilities is critical for developing robust applications, whether you're working with text files, binary files, or custom file formats.

In this Java Tutorial, we will learn How file handling in Java works and we will also see its different operations.

Why is File Handling in Java Required?

File handling is necessary for:
  • Data persistence: Saving data to files assures that it can be retrieved later, even if a program has stopped running.
  • Data communication: Files enable data communication between different programs or systems.
  • Large data storage: Files enable the storage of large datasets that would not fit in memory.
  • Log management: Storing logs in files allows you to follow program activity and troubleshoot difficulties.

Key Concepts: Java I/O and Streams

The key concepts of file handling in Java are Java I/O and streams.Java uses streams to accomplish I/O operations. A stream is a sequence of data. Java supports two types of streams:
  1. Byte Streams: Handle data in raw binary format.
  2. Character Streams: Manage data in the form of characters.

Key Concepts: Java I/O and Streams

1. Byte Streams

Byte streams are used to read and write data on the byte level.
They are handy for working with binary data, such as photos or audio files.
  • InputStream: InputStream reads byte data.
  • OutputStream: OutputStream writes byte data.

InputStream

The Java InputStream class is the ancestor of all input streams. The input stream reads data from a variety of input devices, such as the keyboard and network. InputStream is an abstract class, hence it is not helpful on its own. However, its subclasses serve to retrieve data.
The InputStream class has multiple subclasses, including the following:
  • AudioInputStream
  • ByteArrayInputStream
  • FileInputStream
  • FilterInputStream
  • StringBufferInputStream
  • ObjectInputStream

1. How to Create an InputStream

// Here we are Creating an InputStream
InputStream obj = new FileInputStream();
The FileInputStream class is used to build an input stream.

2. Different Methods of InputStream

Method NameUsage
read()It reads one byte of data from the input stream.
read(byte[] array)()It reads a byte from the stream and stores that byte in the specified array.
mark()Marks the position in the input stream until the data has been read.
available()It returns the number of bytes available in the input stream.
markSupported()Check if the mark() method and the reset() method is supported in the stream.
reset()It returns the control to the point where the mark was set inside the stream.
skips()It skips and removes a particular number of bytes from the input stream.
close()It closes the input stream.

2. Output Stream

The output stream is used to write data to a variety of output devices, including the monitor, file, etc. OutputStream is an abstract class that denotes an output stream. OutputStream is an abstract class, hence it isn't helpful on its own. However, its subclasses are utilized to create data.
The OutputStream class has multiple subclasses, which are listed below:
  • ByteArrayOutputStream
  • FileOutputStream
  • StringBufferOutputStream
  • ObjectOutputStream
  • DataOutputStream
  • PrintStream

1. How to create an OutputStream

// Creating an OutputStream
OutputStream obj = new FileOutputStream();
FileOutputStream is used to produce an output stream.

2. Different Methods of OutputStream

Method NameUsage
write()It writes the specified byte to the output stream.
write(byte[] array)It writes the bytes inside a specific array of the output stream.
close()It closes the output stream.
flush()It forces to write all the data present in an output stream to the destination.

2. Character Streams

Character streams represent data as characters. They are useful for text data, as they ensure appropriate character encoding and decoding.
  • Reader: It reads character data.
  • Writer: It produces character data.

Example

FileReader reader = new FileReader("input.txt");
int data = reader.read();

Core File Handling Classes in Java

Java has a number of classes that simplify file-handling procedures. These classes are found in the"java.io" and"java.nio.file"packages. there are three types of file-handling classes in Java they are as follows.
  1. File Class
  2. FileReader and FileWriter
  3. BufferedReader and BufferedWriter

1. File Class

The File class denotes a file or directory path. It includes methods for creating, deleting, and retrieving information about files and directories.

Example

File file = new File("example.txt");
if (file.exists()) {
    System.out.println("File exists");
} else {
    System.out.println("File does not exist");
}

Java File Class Methods

The table below displays numerous File Class methods:
Method NameDescriptionReturn Type
canRead()It tests whether the file is readable or not.Boolean
canWrite()It tests whether the file is writable or not.Boolean
createNewFile()It creates an empty file.Boolean
delete()It deletes a file.Boolean
exists()It tests whether the file exists or not.Boolean
length()Returns the size of the file in bytes.Long
getName()Returns the name of the file.String
list()Returns an array of the files in the directory.String[]
mkdir()Creates a new directory.Boolean
getAbsolutePath()Returns the absolute pathname of the file.String

2. FileReader and FileWriter

FileReader and FileWriter are used to read and write character data from and to files. They're perfect for working with text documents.

Example of writing data

FileWriter writer = new FileWriter("example.txt");
writer.write("Welcome to Scholarhat!");
writer.close();

Example of reading data:

FileReader reader = new FileReader("example.txt");
int data;
while ((data = reader.read()) != -1) {
    System.out.print((char) data);
}
reader.close();

3. Buffered Reader and BufferedWriter

BufferedReader and BufferedWriter boost performance by buffering input and output streams. They are useful for managing huge files.

Example of reading data with a buffered reader

BufferedReader br = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = br.readLine()) != null) {
    System.out.println("Welcome to ScholarHat");
}
br.close();

Different Operations of File Handling in Java

  • Create File
  • Read File
  • Write File
  • Delete File
  • 1. Create File

    Here, You can create a new file using the File class:
    File file = new File("newFile.txt");
    if (file.createNewFile()) {
        System.out.println("File created successfully.");
    } else {
        System.out.println("File already exists.");
    }
    

    2. Write File

    You can write data to files using FileWriter or BufferedWriter:
    FileWriter writer = new FileWriter("example.txt");
    writer.write("This is file content.");
    writer.close();
    

    3. Read File

    Use FileReader or BufferedReader to read data from files:
    BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();
    

    Delete Files

    You can delete a file using the delete() method of the File class:
    File file = new File("example.txt");
    if (file.delete()) {
        System.out.println("File deleted successfully.");
    } else {
        System.out.println("Failed to delete file.");
    }
    

    Advanced File Operations

    There are two advanced File Operations related to file handling in Java they are as follows
    • Copying and Moving Files
    • File Attributes: Size, Path, and Permissions

    1. Copying and Moving Files

    Java's Files class (from java.nio.file) allows you to efficiently copy and move files:
    Files.copy(Paths.get("source.txt"), Paths.get("destination.txt"));
    Files.move(Paths.get("source.txt"), Paths.get("newLocation.txt"));
    

    2. File attributes

    File attributes include size, path, and permissions. The File class allows you to access file attributes like size, location, and permissions.
    File file = new File("example.txt");
    System.out.println("File size: " + file.length() + " bytes");
    System.out.println("File path: " + file.getAbsolutePath());
    System.out.println("Is file writable? " + file.canWrite());
    

    Working with Different File Formats

    1. Text Files

    Text files contain data in a human-readable format. To work with text files, use character streams (FileReader and FileWriter).

    2. Binary files

    Binary files hold data in a binary format, which is commonly used for photos, movies, and generated code. To handle binary files, use byte streams (FileInputStream and FileOutputStream).

    3. CSV files

    CSV (Comma-Separated Values) files are text files that store tabular data. BufferedReader and FileWriter allow you to read and write CSV files.

    Example of reading CSV data:

    BufferedReader br = new BufferedReader(new FileReader("data.csv"));
    String line;
    while ((line = br.readLine()) != null) {
        String[] values = line.split(",");
        System.out.println(Arrays.toString(values));
    }
    br.close();
    

    Properties Files

    Properties files are used to store configuration data. Java provides the Properties class for reading and writing key-value pairs.
    Properties props = new Properties();
    props.load(new FileReader("config.properties"));
    String value = props.getProperty("key");
    System.out.println("Value: " + value);
    

    Exception Handling in File Operations

    File handling operations frequently throw checked exceptions, such as IOException or FileNotFoundException. To handle these exceptions, utilize a try-catch block.
    try {
        FileReader reader = new FileReader("example.txt");
        int data;
        while ((data = reader.read()) != -1) {
            System.out.print((char) data);
        }
        reader.close();
    } catch (FileNotFoundException e) {
        System.out.println("File not found: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("Error reading file: " + e.getMessage());
    }
    
    Conclusion
    File management in Java offers a reliable method for creating, reading, writing, and manipulating files. Whether you're dealing with text files, binary files, or particular formats such as CSV or properties files, Java's I/O package and java.nio.file package provides diverse capabilities for all file-handling requirements. Properly managing file operations and resolving errors guarantees that your Java applications deal with files in a reliable and fast manner. Also, consider our Full-Stack Java Developer Certification Training Course for better understanding of Java core concepts. Enjoy coding..!

    FAQs

    • Reusability: File handling allows us to preserve the information/data generated after we run the program. 
    • Saves Time: Some programs might require a large amount of input from their users.

    File handling provides a mechanism to store the output of a program in a file and to perform various operations on it.

    You can use Java handlers to respond to received events and execute corresponding business logic.
    Share Article
    About Author
    Shailesh Kumar (Azure Architect and Mentor)

    Shailesh Kumar is a qualified Engineer with 21 Years of IT experience and strong infrastructure management expertise. Delivered successful corporate training to Fortune CMM Level 5 Clients like TCS, Wipro, IBM, Cognizant, Atos, ETC. He is certified in Azure Administration, Azure DevOps, and Microsoft Certified Trainer.

    Accept cookies & close this