×

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 Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

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

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.