Read File Using Java Scanner Class

Read File Using Java Scanner Class explains about the usage of Java Scanner class API.

while (scnr.hasNextLine()) {
	String line = scnr.nextLine();
	System.out.println( lineNum + " : " + line);
	lineNum++;
}

On above code, we are using java.util.Scanner class methods, method scanner.nextLine() is used for reading whole content line by line

Another important method of Scanner class is useDelimiter(), which allows you to change the delimiter accordingly.

Read File Using Java Scanner Class

package com.examples;

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

public class JavaScannerExample {

   
// Java Scanner Class Example
   
public static void main(String[] args) throws FileNotFoundException {

       
// Creating File Object
       
File file = new File("read.txt");

       
// Creating Scanner Object
       
Scanner scnr = new Scanner(file);

       
// Reading each line of file using Scanner class
       
int lineNum = 1;
       
while (scnr.hasNextLine()) {
           
String line = scnr.nextLine();
            System.out.println
(lineNum + " :" + line);
            lineNum++;
       
}
       

    }
}
Output
1 : I am a java programmer
2 : I am a disco dancer

Java Scanner useDelimiter Example

package com.examples;

import java.util.Scanner;

public class ScannerDelimeterExample {
   
public static void main(String[] args) {
       
String text = "I, Am, A, Java, Programmar";

        Scanner in =
new Scanner(text).useDelimiter("\\s*,\\s*");
       
while (in.hasNextLine()) {
           
System.out.println(in.next());
       
}
       
    }
}
Output
I
Am
A
Java
Programmar

 






Your email address will not be published. Required fields are marked *