Friday, July 23, 2021

How to read a text file using Scanner in Java? Example Tutorial

As I told you before that there are multiple ways to read a file in Java e.g. FileReader, BufferedReader, and FileInputStream. You chose the Reader or InputStream depending upon whether you are reading text data or binary data, for example, the BufferedReader class is mostly used to read a text file in Java. The Scanner class is also another way to read a text file in java. Even though Scanner is more popular as a utility to read user input from the command prompt, you will be glad to know that you can also read a file using Scanner. 

Similar to BufferedReader, it provides buffering but with a smaller buffer size of 1KB and you can also use the Scanner to read a file line by line in Java. 

Similar to readLine(), the Scanner class also have nextLine() method which return the next line of the file. Scanner also provides parsing functionality e.g. you can not only read text but parse it into correct data type e.g. nextInt() can read integer and nextFloat() can read float and so on.

The java.util.Scanner is also a newer class compared to BufferedReader, only added on Java 1.5 version, so you can't guarantee its availability on all Java versions, but to be honest in 2016 with Java 8 already over 2 years old, Java 5 is the end of life. So, for most of the practical purposes, Scanner should be taken as granted.

In this article, I'll share a couple of examples of reading a text file using Scanner. It provides an array of next() methods e.g. next(), nextLine(), nextInt(), or nextFloat(). The next() method return the next token where the delimiter is by default space, while nextLine() return next line where line terminator can be \n or \r\n .

You can also see Core Java Volume II - Advanced Features by Cay S. Horstmann to learn more about how Scanner parses the text data while reading.  Anyway, let' see the Scanner example to read a text file to understand more.





How to read text file line by line using Scanner

Here is a sample code example of how you can read a text file line by line using Scanner. It uses nextLine() to read a file line by line.

public static void readTextFileUsingScanner(String file) {
    try {
      Scanner sc = new Scanner(new File(file));
      while (sc.hasNext()) {
        String str = sc.nextLine();
        System.out.println(str);
      }
      sc.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

You can see that we have used hasNext() method to check if there are more lines left and then used nextLine() to actually read the line. Don't forget to close the Scanner once you are done to prevent resource leak. This is one of the recommended coding guidelines for Java programmers to write robust programs, you can also see Java Coding Guidelines: 75 Recommendations for Reliable and Secure Programs for more best practices.

How to read a text file using Scanner in Java?


Btw, you can even use next() to read text file word by word as shown in the example in next section.



Java Program to read a text file using Scanner

Here is our complete Java program which demonstrates usage of both nextLine() and next() methods to read data from a text file in Java. By default, the next() method read file word by word, where words are separated by whitespace. In this example, we will read a text file called "file1.txt", which contains the following lines:

file1.txt
Java, JavaScript, Jython

You can see the file only contains one line but three words which are separated by space. Btw, reading from a file using Scanner is no different than reading an input stream from the keyboard, which is the most popular usage of Scanner class in Java. Only thing changes are the source, in the case of a file, the source is the file itself.

reading text file in Java using Scanner



Reading a text file using Scanner in Java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

/*
 * Java Program read a text file in multiple way.
 * This program demonstrate how you can use FileReader,
 * BufferedReader, and Scanner to read text file,
 * along with newer utility methods added in JDK 7
 * and 8. 
 */
public class ScannerExample {

  public static void main(String[] args) throws Exception {

    // reading a text file line by line using Scanner
    System.out.println("Reading a text file line by line: ");
    Scanner sc = new Scanner(new File("file.txt"));
    while (sc.hasNext()) {
      String str = sc.nextLine();
      System.out.println(str);
    }
    sc.close();


    // reading all words from file using Scanner
    System.out.println("Reading a text file word by word: ");
    Scanner sc2 = new Scanner(new File("file.txt"));
    while (sc2.hasNext()) {
      String word = sc2.next();
      System.out.println(word);
    }

    sc2.close();

  }
}


Output
Reading a text file line by line: 
Java, JavaScript, Jython
Reading a text file word by word: 
Java,
JavaScript,
Jython


That's all about how to read a text file using Scanner in Java. The java.util.Scanner is a nice and powerful class to not only allow you to read user input but allows you to read a text file as well. You can also customize the behavior of the next() method by using nextPattern() method which reads the next matching pattern specified by the regular expression you give to the Scanner class.

You can further read Big Java: Early objects to know more about the capabilities of the Scanner class and how you can take full advantage of this nice utility for reading user input, files, and from other sources.


Other Java File tutorials you may find interesting:
  • Useful differences between BufferedReader and Scanner in Java? (answer)
  • How to read an XML file in Java? (guide)
  • How to read a ZIP file in Java? (tutorial)
  • How to append text to a File in Java? (solution)
  • How to read the XLS and XLSX files in Java? (guide)
  • How to read an XML file as String in Java? (example)
  • How to copy non-empty directories in Java? (example)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to check if a File is hidden in Java? (solution)
  • How to read from a Memory Mapped file in Java? (example)
  • 3 ways to read a file line by line in Java 8? (tutorial)
  • How to read a file in one line in Java 8? (solution)
  • How to read and write a text file in Java? (example)
In the end, using the right tool for the job matters, so use BufferedReader if you just have to read a text file and use Scanner if you also need to parse the data. Also, remember that the buffer size in Scanner is much smaller than Scanner e.g. 1KB compared to 8KB of BufferedReader.

1 comment :

Post a Comment