top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to read a file using scanner type Scanner?

0 votes
605 views
How to read a file using scanner type Scanner?
posted Aug 28, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Use following codes to read the file
import java.io.File;
import java.util.Scanner;

 public class ReadFile {
    public static void main(String[] args) {
     File file = new File("input.txt");
     try {
        Scanner sc = new Scanner(file);
        while (sc.hasNextLine()) {
            int i = sc.nextInt();
            System.out.println(i);
         }
        sc.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

}

answer Aug 30, 2017 by Willow Wilson
@wilson bufferedReader is better or scanner ?
Similar Questions
0 votes

I have a file and I am extracting some data from it using key one by one.After a successful match, I want to reset the scanner object to start from the first line of the file again.

+3 votes

What are the preconditions on C++ type that allows its use in shared memory or read from a file descriptor?

...