reading input till EOF in java

You can do this:

Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
    A[i] = s.nextInt();
    i++;
}

// assuming that reader is an instance of java.io.BufferedReader
String line = null;
while ((line = reader.readLine()) != null) {
    // do something with every line, one at a time
}

Let me know if you run into difficulties.


Here is Java equivalent code using BufferedReader and FileReader classes.

  import java.io.BufferedReader;
  import java.io.FileReader;
  import java.io.IOException;

  public class SmallFileReader {
        public static void main(String[] args) throws IOException {  

Option 1:
String fileName = args[0];
BufferedReader br = new BufferedReader(new FileReader(fileName));
Option 2:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a file name: ");
String fileName = br.readLine();

             //BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
             String line=null;
             while( (line=br.readLine()) != null) {
                    System.out.println(line);  
             }
  }
}  

I made little modification to @Vallabh Code. @tom You can use the first option, if you want to input the file name through command line.
java SmallFileReader Hello.txt
Option 2 will ask you the file name when you run the file.

Tags:

Java

File Io

Eof