Friday, July 16, 2021

How to read file in Java using Scanner Example - text files

Reading a file with Scanner
From Java 5 onwards java.util.Scanner class can be used to read file in Java. Earlier we have seen examples of reading file in Java using FileInputStream and reading file line by line using BufferedInputStream and in this Java tutorial, we will See How can we use Scanner to read files in Java. Scanner is a utility class in java.util package and provides several convenient methods to read int, long, String, double etc from a source which can be an InputStream, a file, or a String itself.

 As noted on How to get input from User, Scanner is also an easy way to read user input using System.in (InputStream) as the source. The main advantage of using Scanner for reading files is that it allows you to change delimiter using the useDelimiter() method, So you can use any other delimiter like comma, pipe instead of white space.



How to Read File in Java - Scanner Example

How to read file in Java 5 using Scanner with ExampleIn this Java program, we have used java.util.Scanner to read file line by line in Java. We have first created a File instance to represent a text file in Java and then we passed this File instance to java.util.Scanner for scanning. 

The scanner provides methods like hasNextLine() and readNextLine() which can be used to read file line by line. It's advised to check for next line before reading next the line to avoid NoSuchElementException in Java.  

Here is the complete code example of using Scanner to read text files in Java :


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 *
 * Java program to read files using Scanner class in Java.
 * java.util.Scanner is added on Java 5 and offers a convenient method to read data
 *
 * @author
 */

public class ScannerExample {

    public static void main(String args[]) throws FileNotFoundException {
 
        //creating File instance to reference text file in Java
        File text = new File("C:/temp/test.txt");
     
        //Creating Scanner instance to read File in Java
        Scanner scnr = new Scanner(text);
     
        //Reading each line of the file using Scanner class
        int lineNumber = 1;
        while(scnr.hasNextLine()){
            String line = scnr.nextLine();
            System.out.println("line " + lineNumber + " :" + line);
            lineNumber++;
        }      
   
    }  
 
}

Output:
line 1 :--------------------- START------
-----------------------------------------------
line 2 :Java provides several way to read files.
line 3 :You can read file using Scanner, FileReader,
FileInputStream and BufferedReader.
line 4 :This Java program shows How to read file using java.util.Scanner class.
line 5 :--------------------- END-----------------------
---------------------------------

This is the content of test.txt file exception line numbers. You see it doesn't require much coding to read file in Java using Scanner. You just need to create an instance of Scanner and you are ready to read file.

Other Java IO tutorials you may like

15 comments:

  1. import java.io.FileNotFoundException;
    Why is this line put ?? What is the function of it??

    ReplyDelete
    Replies
    1. Its a library in order the compiler to understand what is File for example

      Delete
    2. It's a library, contains the class FileNotFoundException which is used for throwing a exception in case of not find any input text file.

      Delete
    3. The statement
      import java.io.FileNotFoundException;
      just makes it easier to use the Exception class java.io.FileNotFoundException. It doesn't import any class, it just makes a name easier to use. You just need to write FileNotFoundException instead of the full name.
      So it doesn't have anything to do with any Java libraries (Jar files).

      When the program create a new File object, it will throw a java.io.FileNotFoundException object which contains an error code if the named file doesn't exists.

      As there are no try ... catch that handles that exception in the main method, the method main must then be declared to be expected to generate such an error to everyone that calls the main method.

      Delete
  2. Here is the old way to read a plain text file in Java. It uses FileInputStream instead of FileReader to read text file.

    ReplyDelete
  3. I want to clean & scaning temp file in j2me. What is the code of scaning and cleaning

    ReplyDelete
  4. Hello, I am making a very slow progress learning java.

    Would you be able to help me out and let me know why my data is not displayed after writing the code as below? I am trying to read in a ppm picture, which is white and black and where 255 stands for white and 0 for black. I will need to calculate the number of white lines that are longer than 1/3 of the table size:

    public
    class test {



    public static final int X = 512;
    int count = 0;
    int a = 255;

    public static void main(String[] args){
    int[] data = getData ("C:\\Users\\Joannna\\Desktop\\inData.ppm");
    System.out.println(data.length);
    System.out.println(data);
    }

    public static int[] getData(String path){
    try{
    Scanner scanner = new Scanner(new File("C:\\Users\\Joannna\\Desktop\\inData.ppm"));
    int [] data = new int [X*X];
    int i = 0;
    while(scanner.hasNextInt()){
    data[i++] = scanner.nextInt();
    scanner.nextInt();
    scanner.nextInt();
    }
    return data;
    }catch(Exception io){
    System.out.println(io);
    return null;
    }
    }

    }

    ReplyDelete
  5. java.please

    //write code with proper exceptions handling read the contents
    //ef the above file using methods of the scanner class

    ReplyDelete
  6. What if I want the scanner object to start exactly from line 3?, To start reading the lines from line 3 downwards?

    ReplyDelete
    Replies
    1. I don't remember top of my head but there should be an option to move Scanner pointer, check the Java documentation, you will definitely find something.

      Delete
  7. HOW TO FETCH THE DATA USING SCANNER CLASS IN JAVA ...PLZ DESCRIBE AS COMMENT IN CODE

    ReplyDelete
    Replies
    1. Hello Abhishek, I have shared a lot of exampls of Scanner class, you can search for it
      here are a couple of them
      https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html
      http://javarevisited.blogspot.sg/2012/12/how-to-read-input-from-command-line-in-java.html#axzz5DmwFLA1K

      Delete
  8. how do we save it to a new file? so I am able to print it and is displayed perfectly. But now I want to save it to a new file for me to open it as a text. Thank You

    ReplyDelete
    Replies
    1. you can just write into the file and when you flush it will be saved. See here for an example about how to write data into a text file in Java

      Delete

Feel free to comment, ask questions if you have any doubt.