Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Multiple Ways of File Handling
2.1.
1.) Using BufferedReader class
2.1.1.
Syntax
2.1.2.
Code
2.1.3.
Output 
2.2.
2.) Using Scanner Class
2.2.1.
Code
2.2.2.
Output 
2.3.
3.) Using File Reader Class
2.3.1.
Code
2.3.2.
Output
2.4.
4.) Reading the whole file in a List
2.4.1.
Code 
2.4.2.
Output 
3.
Frequently Asked Questions
4.
Conclusion
Last Updated: Mar 27, 2024

File Handling in Java

Author Aditya Anand
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Welcome Readers! A text file can be written and read in a variety of ways. This is necessary when working with a large number of apps. You can read a plain text file in Java using FileReader, BufferedReader, or Scanner, for example. Every utility, for example, offers something unique. Data is buffered for rapid reading with BufferedReader, while parsing is done with Scanner.

Let’s dive into it and we hope you learn a lot.

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

  1. 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.

     
  2. 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.

     
  3. 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. 

     
  4. 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 Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Previous article
Creation of Files in Java
Next article
How to write on files in java
Live masterclass