top

Search

Java Tutorial

.

UpGrad

Java Tutorial

File Handling in Java

Overview

Java, one of the most popular programming languages, supplies extensive support to numerous functional operations like file handling, database, sockets, etc. File handling in Java is a crucial function that allows you to conduct different tasks on a stored file, such as writing, reading, etc. 

This tutorial presents a thorough synopsis of file handling and its functionality in Java. 

Why is File Handling Required?

You can work with files in Java by using the File Class inside the java.io package. Generating an object of the class and then adding a specified name to the file allows you to use the File Class. File handling in Java primarily stands for reading from, followed by writing data to a particular file. 

Classes of File Handling 

The File Class lets you perform various operations on different file formats once an object of the class with a specific filename or directory name is created. File handling presents you with several benefits, such as:

  • It is an integrated section of any programming language. File handling in Java example programs shows how you can store output values from any particular program inside a file, allowing you to monitor necessary operations on the file and other benefits.

  • It implies the function of reading and writing data to files, which eventually helps simplify the operations performed in Java. 

Java uses the concept of streams to conduct I/O operations on its files. Hence, the streams play an important role in the file-handling operations of Java. 

What are Streams in Java?

In Java, a stream is a sequence of data used to perform I/O operations on files. Based on the functional aspects, streams can be categorized into two types, namely:

  • Input Stream: The superclass of every input stream is known as the InputStream Class in Java. It helps in reading the data received from input devices.

  • Output Stream: The output stream is used to write data or add files to the output devices. The OutStream Class abstractly forms a superclass that represents the output stream. 

The stream API is used for processing groups of data. JavaScript can programmatically access the streams of data received over the network using stream API. It also allows Java to process the data streams as per the developer's requirements. 

Stream API can also be divided into two categories depending on the data type, which are:

  • Byte Stream: It is used to read or write byte files, including byte input and output streams

  • Character Stream: It helps to read and write character data which can be further classified depending on the input and output operations. 

File Handling in Java Example Programs

Copying a File

Let us write a program that copies the contents of a file named "source.txt" to another file named "destination.txt".

We will first create the source.txt file and put the text ‘upGrad teaches programming.’ in this file. It is also important to note that we must create the java (upGradTutorials.java) file in the same directory as the source.txt file.

Then, we will run the program below:

import java.io.*;

public class CopyFileExample {
    public static void main(String[] args) {
        try {
            File sourceFile = new File("source.txt");
            File destinationFile = new File("destination.txt");


            FileReader fileReader = new FileReader(sourceFile);
            FileWriter fileWriter = new FileWriter(destinationFile);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


            String line;
            while ((line = bufferedReader.readLine()) != null) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }


            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Once we run the program, a new file destination.txt will get created in the directory with the same text.

The code begins by creating two File objects: sourceFile represents the source file ("source.txt"), and destinationFile represents the destination file ("destination.txt"). A FileReader and FileWriter are created to read from the source file and write to the destination file. BufferedReader and BufferedWriter are used for efficient reading and writing.

Inside the while loop, each source file line is read using readLine() and written to the destination file using write(). The newLine() method is used to insert line breaks. The loop continues until there are no more lines to read from the source file. Finally, the BufferedReader and BufferedWriter are closed to flush the buffers and release system resources.

Reading a File

Now, let us write a program that reads the contents of a file named "upGrad.txt" and prints each line to the console. 

We will first create the upGrad.txt file and put the text ‘upGrad teaches Java programming.’ inside this file. Then, we will create the java (upGradTutorials.java) file in the same directory as the txt file.

Once we run the program, it will read the contents of the upGrad.txt file and print each line to the console.

import java.io.*;

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            File file = new File("upGrad.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program begins by creating a File object representing the file "upGrad.txt". Then, a FileReader is created to read the contents of the file, and a BufferedReader is used to read the text efficiently. Within a while loop, each line of the file is read and stored in the variable line.

The loop continues until there are no more lines to read (i.e., readLine() returns null). For each line, the program prints it to the console. Finally, the BufferedReader is closed to release system resources and handle any potential exceptions.

Writing to a File

We have learned how to read files in Java, let us now learn how to write a program that will first create a ‘upGrad.txt’ file and then write the two strings of text ‘upGrad teaches programming.’ and ‘upGrad teaches Java.’ in that txt file.

Contents of the created txt file:

import java.io.*;

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            File file = new File("upGrad.txt");
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            bufferedWriter.write("Hello, World!");
            bufferedWriter.newLine();
            bufferedWriter.write("This is a sample text.");

            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program begins by creating a File object representing the file "upGrad.txt". Next, a FileWriter is created to write the file's contents, and a BufferedWriter is used to write the text efficiently.

The program then uses the write() method of the BufferedWriter to write the string "upGrad teaches programming." to the file. The newLine() method moves the cursor to the next line. Another string, "upGrad teaches Java." is written to the file. Finally, the BufferedWriter is closed to flush the buffer and release system resources.

Java File Methods

Here are some commonly used methods in the File class for file handling:

  • exists(): Checks if the file or directory exists.

  • getName(): Retrieves the name of the file or directory.

  • isDirectory(): Checks if the given file is a directory.

  • isFile(): Checks if the given file is a regular file.

  • length(): Returns the size of the file in bytes.

  • getParent(): Retrieves the parent directory of the file or directory.

  • canRead(): Checks if the file or directory can be read.

  • canWrite(): Checks if the file or directory can be written to.

  • isHidden(): Checks if the file or directory is hidden.

  • lastModified(): Returns the timestamp when the file was last modified.

  • delete(): Deletes the file or directory.

  • mkdir(): Creates a new directory.

  • mkdirs(): Creates a new directory and its parent directories if they do not exist.

  • list(): Returns an array of file names in the directory.

  • listFiles(): Returns an array of File objects representing files in the directory.

  • getAbsolutePath(): Returns the absolute path of the file or directory.

  • renameTo(File dest): Renames the file or directory to the specified destination file.

  • createNewFile(): Creates a new empty file.

  • listFiles(FileFilter filter): Returns an array of File objects representing files in the directory that satisfy the specified filter.

  • toURI(): Returns a URI object representing the file or directory.

File Operations in Java

Creating a File

This code creates a new file named "upGrad.txt" using the createNewFile() method. If the file is successfully created, it prints a message indicating so. If the file already exists, it prints a message stating it already exists.

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

public class upGradTutorials {
    public static void main(String[] args) {
        try {
            File file = new File("upGrad.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Deleting a File

This code deletes a file named "upGrad.txt" using the delete() method. If the file is successfully deleted, it prints a message indicating so. If the deletion fails, it prints a message stating that the file couldn't be deleted.

import java.io.File;


public class upGradTutorials {
    public static void main(String[] args) {
        File file = new File("upGrad.txt");
        if (file.delete()) {
            System.out.println("File deleted: " + file.getName());
        } else {
            System.out.println("Failed to delete the file.");
        }
    }
}

Renaming a File

This code renames a file named "example.txt" to "upGrad.txt" using the renameTo() method. If the renaming is successful, it prints a message indicating so. If the renaming fails, it prints a message stating that the file couldn't be renamed.

import java.io.File;

public class upGradTutorials {
    public static void main(String[] args) {
        File oldFile = new File("example.txt");
        File newFile = new File("upGrad.txt");
        if (oldFile.renameTo(newFile)) {
            System.out.println("File renamed successfully.");
        } else {
            System.out.println("Failed to rename the file.");
        }
    }
}

Checking File Attributes

This code checks the attributes of a file named "upGrad.txt" using the File class. It first checks if the file exists using the exists() method. If the file exists, it prints the file name, absolute path, size, last modified timestamp, and whether it is a directory or a regular file. If the file doesn't exist, it prints a message indicating it doesn't exist.

import java.io.File;

public class upGradTutorials {
    public static void main(String[] args) {
        File file = new File("upGrad.txt");
        if (file.exists()) {
            System.out.println("File name: " + file.getName());
            System.out.println("File path: " + file.getAbsolutePath());
            System.out.println("File size: " + file.length() + " bytes");
            System.out.println("Last modified: " + file.lastModified());
            System.out.println("Is directory? " + file.isDirectory());
            System.out.println("Is file? " + file.isFile());
        } else {
            System.out.println("File does not exist.");
        }
    }
}

Conclusion

You can perform several operations on a file in Java. The four major operations include creating a file, getting file information, writing to a file, and reading from a file. These activities can be easily accomplished using the different techniques of file handling in Java. 

A comprehensive course can help you if you want to gain deeper insight into file handling and other operations in Java. upGrad offers curated courses on Java that can increase your expertise on the subject. Enrolling in these courses allows you to gain more knowledge about the core Java concepts.

FAQs

1. What are file handling methods?

File handling is the process of storing the available data or information in a file with the assistance of a program. In Java, you can store the entire available data of a program inside a file with the help of file handling. The data can be retracted or fetched back from the files whenever you need them, whereas using file handling in Java allows you to operate the stored files in another program.

2. How to perform file handling in Java?

You can get all the classes required for performing every input and output operation in Java from the java.io package. The Java I/O API allows you to work with file handling in Java.

3. Why is a string immutable in Java?

Strings that contain the same values try to minimize unwanted copies of the content, which makes them share the storage of a single pool. Once a string is created, its internal content cannot be further changed since adding any changes to its values leads to creating a new string. This explains why strings in Java are immutable or unchangeable. 

Leave a Reply

Your email address will not be published. Required fields are marked *