×

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish the above goal:

  • bufferedReader
  • scanner class

BufferedReader

This class comes under the java.io package, which is implemented when there is a need to read text from a character-input stream. It buffers characters to provide an efficient reading of the input, such as characters, arrays, and lines.

The buffer size is determined by the user or an already defined size which is, by default, that can also be used as it is large enough to serve maximum cases. It uses the concepts of inheritance to inherit the reader class. It implements the following interfaces:

  • Closable
  • AutoClosable
  • Readable

Following is an example that shows how BufferReader class is declared (BufferedReader Syntax)

Public class BufferedReader extends Reader (Where public class is an access specifier)

BufferReader Constructors

BufferReader has two types of constructors, which are as follows:

1. BufferReader( Reader in)

This will use the default size of Bufferedreader.

2. BufferReader(Reader in, int n)

This will use the size specified by the user where “n” represents the size of the constructors. It throws IllegalArgumentException if the size of the array is less than and equal to zero.

BufferReader Methods

Following are the methods of BufferReader.

  1. Void Close(): Other methods, such as read() and mark(), will throw an IOException if this method is used.
  2. Void mark(): It marks the current position.
  3. Boolean markSupported(): As the name suggests, the above method checks or tells that the stream supports marl() operation. It overrides the mark supported in class Reader.
  4. Int read( ): It is used when only 1 character is to be read. It overrides read in class Reader.
  5. Int read( char[] buff, int off, int l): It is implemented when there is a need to read a portion of characters from the array.
    • Debuff – destination buffer.
    • Off – it is the point from where sorting characters get initiated.
    • L – the number of characters you can read.
  6. String readLine(): In this case, a whole line of text is to be read.
  7. Boolean ready(): As the name suggests, the above method checks and tells whether the input is ready to be read. It overrides the ready class Reader.
  8. Void reset(): As the name suggests, the stream is reset to its most recent mark.
  9. Long skip( long n): It is implemented when there is a need to skip characters. In the above syntax, n represents the number of characters to be skipped. It overrides skip in class Reader.

Example

Java Read Line by line

The above snippet of code is an example of how one can use BufferedReader to read contents from a file and print it.

In the first line, we have specified the path of the file. The file contains some text. We check whether the file is empty or not and then print the file's content. We can see files getting printed in the console as we run the program.

Java Read Line by line

When to use BufferedReader to read files

  • When we need a synchronous concept.
  • When we are working with multiple threads.
  • When we need to write millions of lines.

Scanner

In java, there is another way of taking input which is known as a Scanner. Java.Util.Scanner class can parse primitive types and strings. It implements the following functions:

Closable

Autoclavable

Iterator< string>

How Scanner Class Works

It takes the entire line and divides it into small elements. For example, the following is an input string.

MY name is Sahil

The scanner object will read the whole line and divide the above line into four elements or tokens, which are: " My ", " name ",  " is " and " Sahil ”. Then object iterates all the above token and read each element depending upon the method type declared in the program.

Constructors

Following are the constructors provided by the Scanner class in java.

  • Scanner (File Source)

This function is used to read data from a File object representing a file.

  • Scanner ( InputStream source)

To read data from an InputStream, call this method.

  • Scanner (Path source)

This method reads the file that the object specifies.

Example

Following a small piece of code is an example of the Scanner class's implementation.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class a {
public static void main(String[] args) {
        File file = new File("d://sample.txt");
        try {


            Scanner st  = new Scanner(file);
            while (st.hasNextLine()) {
                String output = st.nextLine();
System.out.println(output);
}
        } catch (FileNotFoundException e) {
            e.printStackTrace();
}
    }
}
  • First, we imported the necessary packages to implement the scanner class.
  • Then we created an instance of file for the sample.txt file.
  • After that, we created a Scanner object which will read the data which is inside the specified file ( Sample.txt )
  • We have used the hasNextLine() method to read text line by line.
  • Then the file’s content is being read and stored in the output string, and we printed the output (the reference variable of string) to see the results in the console, shown below. 
Java Read Line by line

In the above code, we used a method named hasNextLine().

It is a Scanner class method with a boolean return type. It is implemented when there is a need to check wheater there is another line in the input. It was used in the while loop. If it returned true, the while loop has run again to read the content inside the file. But the file specified by us had only one line of text – Hello Everyone. Thus after running once, the hasNextLine() method returns false and makes the while loop terminate.

Comparison in Scanner class features with Buffered Reader class.

BufferedReaderScanner
It has a larger buffer memory.                                   It has a smaller buffer memory.
It is synchronous.                                                       It is not synchronous.   
It is comparatively faster.                                            It is comparatively slower. 
It should be used when we are working with multiple threads.                                                              It should be used when we are not working with multiple threads.  

Related Topics

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Best Java Libraries

One of the most widely used programming languages is Java. Java has a large number of libraries, including the standard Java library that includes libraries such as java.lang, java.util, and...

7 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.