Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is File Handling in Java?
3.
Why File Handling is Required?
4.
Streams in Java
5.
Java File Class Methods
6.
File Operations
6.1.
Create a File
6.2.
Get File Information
6.3.
Write to a File
6.4.
Read from a File
6.5.
Delete a File
7.
Multiple Ways of File Handling
7.1.
1.) Using BufferedReader class
7.1.1.
Syntax
7.1.2.
Code
7.1.3.
Output 
7.2.
2.) Using Scanner Class
7.2.1.
Code
7.2.2.
Output 
7.3.
3.) Using File Reader Class
7.3.1.
Code
7.3.2.
Output
7.4.
4.) Reading the whole file in a List
7.4.1.
Code 
7.4.2.
Output 
8.
Frequently Asked Questions
8.1.
What is meant by file in Java?
8.2.
How to work with files in Java?
8.3.
What is a file object in Java?
8.4.
Is JDK required to run a Java program?
8.5.
How to list all the existing files in a directory in Java?
9.
Conclusion
Last Updated: Jul 6, 2024
Easy

File Handling in Java

Author Aditya Anand
0 upvote

Introduction

In Java programming, file handling is an essential skill that every developer must master. Whether you're building simple applications or complex systems, the ability to read from and write to files is crucial for tasks such as data storage, configuration management, and processing large datasets. Java provides a robust set of classes and methods in its standard library to facilitate various file operations seamlessly.

This blog will guide you through the fundamentals of file handling in Java.

File Handling in Java

What is File Handling in Java?

File handling in Java refers to the process of managing data storage and retrieval operations, including reading from and writing data to a file. This involves creating, opening, reading, writing, and closing files using various classes and methods provided by the Java I/O (Input/Output) package.

Why File Handling is Required?

File handling is required to facilitate the storage and retrieval of data in a persistent format. It enables applications to save data permanently, allowing for data analysis, record-keeping, configuration management, and transfer of information between systems. Effective file handling ensures data integrity, security, and efficient processing, making it a critical aspect of software development.

Streams in Java

In Java, streams are sequences of data that support input and output operations. Streams can handle data flow for both byte-based and character-based data. The primary types of streams are:

  • Input Streams: Used to read data from a source (e.g., files, network connections).
  • Output Streams: Used to write data to a destination (e.g., files, network connections).

Java provides several classes for working with streams, such as FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, ObjectInputStream, and ObjectOutputStream.

Java File Class Methods

The File class in Java provides various methods for file operations. Here's a summary:

MethodReturn TypeDescription
createNewFile()booleanCreates a new, empty file if it does not already exist.
delete()booleanDeletes the file or directory denoted by this abstract path name.
exists()booleanTests whether the file or directory exists.
getName()StringReturns the name of the file or directory.
getAbsolutePath()StringReturns the absolute pathname string.
length()longReturns the length of the file in bytes.
isDirectory()booleanTests whether the file is a directory.
list()String[]Returns an array of strings naming the files in the directory.
mkdir()booleanCreates a directory named by this abstract path name.

File Operations

Create a File

Creating a file in Java involves using the createNewFile() method from the File class. Here's an example:

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();
        }
    }
}

Get File Information

To retrieve file information, you can use methods such as getName(), getAbsolutePath(), length(), and isDirectory(). Here's an example:

import java.io.File;

public class FileInfoExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.exists()) {
            System.out.println("File name: " + file.getName());
            System.out.println("Absolute path: " + file.getAbsolutePath());
            System.out.println("File size in bytes: " + file.length());
            System.out.println("Is directory: " + file.isDirectory());
        } else {
            System.out.println("The file does not exist.");
        }
    }
}

Write to a File

Writing to a file can be done using classes like FileWriter and BufferedWriter. Here's an example:

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

public class WriteToFileExample {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("example.txt");
            writer.write("Hello, World!");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Read from a File

Reading from a file can be done using classes like FileReader and BufferedReader. Here's an example:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFromFileExample {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Delete a File

To delete a file, you can use the delete() method from the File class. Here's an example:

import java.io.File;

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

Multiple Ways of File Handling

Java provides multiple ways to handle files, in this section, we will see all those methods with an example code.

Methods:

  • Using BufferedReader class
  • Using Scanner class
  • Using File Reader class
  • Reading the whole file in a List

1.) Using BufferedReader class

This method reads text from a stream of characters. It buffers characters, arrays, and lines for faster reading. The buffer size can either be set or utilised by default. The default value is sufficient for most purposes. In general, every read request made to a Reader is followed by a read request to the underlying character or byte stream. As a result, it's a good idea to wrap a BufferedReader around any Reader whose read() operations are likely to be expensive, such as FileReaders and InputStreamReaders, as demonstrated below: 


Syntax

BufferedReader in = new BufferedReader(Reader in, int size);

Code

// Imports
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
// FileReading class
public class FileReading {
 
    public static void main(String args[]){
        String filename = "input.txt";
        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(new FileReader(filename));
            System.out.println("-----------------File contents--------------------\n");
            while( (line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Invalid Path!");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Unable to read the file.");
            e.printStackTrace();
        }
    }
}

Output 

2.) Using Scanner Class

A simple text scanner that uses regular expressions to parse primitive types and strings. A delimiter pattern, which by default matches whitespace, is used by a Scanner to break its input into tokens. The generated tokens can then be transformed into different types of values.

Code

import java.io.File;
import java.util.Scanner;
public class FileReading {
   public static void main(String args[]) throws Exception {
      //Creating the File object
      File file = new File("D:\\codes\\Competitive\\input.txt");
      //Creating a Scanner object
      Scanner sc = new Scanner(file);
      //StringBuffer to store the contents
      StringBuffer sb = new StringBuffer();
      //Appending each line to the buffer
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine());
      }
      System.out.println(sb);
   }
}

Output 

Try it by yourself on Java Online Compiler.

3.) Using File Reader Class

Reading character files is made easier using this class. The default character encoding and byte-buffer size are assumed to be appropriate by the constructors of this class.

The following are the constructors defined in this class:

  • FileReader(File file): Creates a new FileReader with the File to read from
  • FileReader(FileDescriptor fd): Creates a new FileReader with the File to read from.
  • FileReader(FileDescriptor fd): Creates a new FileReader with the File to read from FileReader( Given a FileDescriptor to read from, 
  • FileReader(String fileName): Given the name of the file to read from, creates a new FileReader.

Code

import java.io.FileReader;  
public class FileReading {  
    public static void main(String args[])throws Exception{    
          FileReader fr=new FileReader("D:\\codes\\Competitive\\input.txt");    
          int i;    
          while((i=fr.read())!=-1)    
          System.out.print((char)i);    
          fr.close();    
    }    
}    

Output

You can also check about Java Tokens here.

4.) Reading the whole file in a List

Read the entire contents of a file. When all bytes have been read or an I/O error or other runtime exception has been thrown, this procedure guarantees that the file is closed. The supplied charset is used to decode the file's bytes into characters.


As line terminators, this approach acknowledges the following:

\u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED

\u000A, LINE FEED, \u000D, CARRIAGE RETURN

Code 

// Imports

import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.io.*;

// FileReading class
public class FileReading
{

    // readFileInList class
    public static List<String> readFileInList(String fileName)
    {
 
        List<String> total_lines = Collections.emptyList();
        try
        {
        total_lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        }
 
        catch (IOException e)
        {
        e.printStackTrace();
        }
        return total_lines;
    }

    // Main class
    public static void main(String[] args)
    {
        List lis = readFileInList("D:\\codes\\Competitive\\input.txt");
 
        Iterator<String> iterator = lis.iterator();
        while (iterator.hasNext())
        System.out.println(iterator.next());
    }
}

Output 

Check out this article - File System Vs DBMS, and Duck Number in Java.

Must Read: Java System Out Println, Why is Java Platform Independent

Frequently Asked Questions

What is meant by file in Java?

A file in Java is a resource for storing data permanently on a disk, enabling reading from and writing data to a persistent storage medium.

How to work with files in Java?

We can work with files in Java using the File Class. The java.io package contains this File Class. To use the File class, first, create an object of the class and then specify the file's name.

What is a file object in Java?

Working with files and directories is possible using this object. Creating a file object in Java is not the same as creating a file. A file object, on the other hand, is an abstract representation of a file or directory pathname (specified in the parenthesis). The createNewFile () method can be used to create a new file.

Is JDK required to run a Java program?

JDK is a development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required. 

How to list all the existing files in a directory in Java?

This class provides a list () (returns names) and ListFiles (returns File objects) with several versions to acquire a list of all the existing files in a directory. The names of all the files and folders in the path represented by the current (File) object are returned in a String array by this function.

Conclusion

In this article, we have extensively discussed File Handling in Java with example codes.

We have learned about file objectsBufferedReader class, Scanner class, and File Reader Class.

We hope that this blog has helped you enhance your knowledge regarding how to handle files in java and if you would like to learn more, check out our articles on The Creation of files in javaException handling in java. Do upvote our blog to help other ninjas grow.


Head over to our practice platform Code360 to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Live masterclass