Saturday, March 2, 2024
HomeJava2 Methods to Learn a Textual content File in Java? BufferredReader and...

2 Methods to Learn a Textual content File in Java? BufferredReader and Scanner Examples


You possibly can learn a textual content file in Java by utilizing both Recordsdata, BufferedReader or Scanner class. Each lessons present handy strategies to learn a textual content file line by line e.g. Scanner gives nextLine() methodology and BufferedReader gives readLine() methodology. In case you are studying a binary file, you need to use FileInputStream. By the way in which, when you’re studying textual content information, you additionally want to offer character encoding, in the event you do not then the platform’s default character encoding is used. In Java IO, streams like InputStream are used to learn bytes, and Readers like FileReader are used to learn character information.
BufferedReader is the normal approach to learn information as a result of it reads file buffer by buffer as an alternative of character by character, so it is extra environment friendly in case you are studying giant information. BufferedReader can also be there from JDK 1 itself whereas Scanner was added to Java 5.

The Scanner has extra options than BufferedReader, in relation to file studying, for instance, you’ll be able to specify any delimiter as an alternative of the brand new line, which isn’t doable with BufferedReader. Java 7 added a brand new File API, which makes studying/writing from the file even simpler.

It is also doable to learn all the file in a single line in Java 7, however given a lot of the initiatives are nonetheless working on Java 6, it is good to find out about these two methods to learn a textual content file in Java. For Java newcomers, I additionally counsel referring to a great e-book like Cay S. Horstmann, Core Java Quantity 1 and a couple of to study the fundamentals of Java programming.

Learn how to learn a textual content file in Java? Examples

You possibly can learn a textual content file within the Java program by utilizing BufferedReader and Scanner and we’ll focus on steps to learn a file on this article. First, we’ll see the way to use the Scanner class to learn a file line by line in Java, after which we’ll study the way to use BufferedReader class to do the identical.

Instance 1 – Studying File utilizing Scanner in Java

Scanner class is outlined in java.util bundle, so step one is to import this class into your Java program. When you imported this class, you’ll be able to create an object of Scanner by passing a FileInputStream to it, pointing to the file you need to learn. 

Now you might be all set to learn a textual content file line by line in Java. The scanner gives a technique known as hasNextLine() which returns true if the file has another line to learn.

This verify is platform-independent so it’ll work in each Home windows and UNIX regardless that the road separator is totally different in these two working techniques e.g. line separator is n in Home windows and rn in UNIX. 

You possibly can learn information from the file by calling nextLine() methodology, it will return the subsequent line and advance the file pointer to the subsequent line. This methodology returns a String object representing a line within the file. You need to use a whereas() loop as proven in our first instance, to learn all strains from information one after the other.

You can even see Core Java Quantity 2 – Superior Options by Cay S. Horstmann to study extra about the way to use Scanner to learn a file in Java.

Instance 2 – Studying Textual content File utilizing BufferedReader in Java

BufferedReader gives one other approach to learn information line by line in Java. It follows a decorator sample and provides buffering functionality to an present reader. You possibly can create an object of InputStreamReader by passing FileInputStream, pointing to the textual content file you need to learn. 

Optionally, you may as well present character encoding to the InputStreamReader, in the event you do not then it’ll use the platform’s default character encoding. InputStreamReader truly acts as a bridge between streams and reader lessons.

After getting an object of BufferedReader, you’ll be able to name the readLine() methodology to learn the subsequent line from the file. This methodology returns a String object containing information from a file, if there is no such thing as a extra line to learn then this methodology return null. Through the use of this correctly, you’ll be able to write some time loop to learn a file line by line in Java, as proven in our second instance.

Although I’ve not closed the buffered reader right here, it is best to do it in your actual manufacturing code, as prompt earlier on the fitting approach to shut streams in Java. It is higher to name the shut() methodology on the lastly block. In case you are on Java 7, think about using try-with-resource assertion to mechanically shut sources as soon as you might be executed with it. You can even use the Recordsdata class to learn entire file in a single line.

How to read text file in Java using BufferedReader and Scanner

Java Program to learn a file line by line in Java

Right here is our full Java program to learn a file in Java. This program incorporates two examples, the primary instance exhibits the way to learn a textual content file utilizing the Scanner class and the second instance exhibits the way to learn a file utilizing BufferedReader class. 

Each lessons are outlined in java.util bundle so you want to import them earlier than utilizing them. In case you are coding in Eclipse then don’t fret, Eclipse will deal with it. With a purpose to run this program from the command line,  create a  Java supply file with the title FileReaderDemo.java and write this program there. 

As soon as you might be executed with it, you’ll be able to comply with the steps given on the way to run Helloworld in Java to run this program from the command line. In case you are utilizing Eclipse IDE, then simply choose a Java undertaking and copy-paste this code there, Eclipse will take care remainder of it. To run a program in Eclipse, simply right-click and choose “Run as Java Program”.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/**
 * Java program to learn File in Java. It display two methods by easy instance,
 * one makes use of java.util.Scanner class and different by utilizing java.io.BufferedReader
 * class.
 *
 * @creator http://java67.blogspot.com
 *
 */

public class FileReaderDemo{

    public static void important(String args[]) throws IOException {

        ultimate String FILE_NAME = "C://temp//GDP.txt";

        // 1st approach to learn File in Java - Utilizing Scanner
        Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));
        whereas (scnr.hasNextLine()) {
            System.out.println(scnr.nextLine());
        }
        scnr.shut();

        // 2nd approach to learn File in Java - Utilizing BufferedReader
        BufferedReader buffReader = new BufferedReader(
             new InputStreamReader(new FileInputStream(FILE_NAME)));
        String line = buffReader.readLine();
        whereas (line != null) {
            System.out.println(line);
            line = buffReader.readLine();
        }
    }
}

Output:

United States   18,390.900
China           15,923.626
India           5,750.467      
Japan           5,021.990      
Germany         3,440.437      
Russia          2,827.978      
Brazil          2,656.858      
United Kingdom  2,562.320      
France          2,416.128    
Mexico          2,040.222

That is all about the way to learn a textual content file in Java utilizing BufferedReader and Scanner. Use Scanner in case you are working on Java 5 or Java 6, or use BufferedReader in case you are working on Java 1.4. You need to use the Recordsdata class to learn textual content information from Java 7 onward. 

In the event you like this tutorial and to study extra about Recordsdata and directories in Java, You can even check out the next Java tutorials :

  • Learn how to learn XLS and XLSX information in Java utilizing Apache POI? (instance)
  • Learn how to create a file and listing in Java? (answer)
  • Learn how to learn XML information in Java utilizing JDOM Parser? (answer)
  • How do you employ the Scanner class in Java? (instance)
  • Learn how to use BufferedReader class in Java? (demo)
  • How do I learn InputStream as String in Java? (answer)
  • Learn how to learn JSON Recordsdata in Java? (answer)
  • How do I learn enter from the console in Java? (instance)

Remember to shut the Scanner and BufferedReader object as soon as you might be executed with it. Additionally, present a personality encoding in case your file’s encoding is totally different than the platform’s character encoding.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments