Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading input till EOF in java

Tags:

java

file-io

eof

In C++ if I wish to read input till the EOF I can do it in the following manner

while(scanf("%d",&n))
{
    A[i]=n;
    i++;
}

I can then run this code as ./a.out < input.txt. What is the java equivalent of this code?

like image 241
zer0nes Avatar asked Dec 18 '12 06:12

zer0nes


People also ask

How to read till end of file Java?

The readUtf8Line() method reads the data until the next line delimiter – either \n , \r\n , or the end of the file. It returns that data as a string, omitting the delimiter at the end. When it encounters empty lines, the method will return an empty string. If there isn't no more data to read, it will return null .

How to take the input till the end of the last line?

You need to make a counter and make a boolean variable. if counter exceeds the number of test cases read, then make the boolen true. and in while loop you need to give the boolean while(boolean_value); as soon as all test cases are read and you make boolean true, while loop will exit.

What is EOF in Java?

Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream.

How to read the next line in text in Java?

To read the line and move on, we should use the nextLine() method. This method advances the scanner past the current line and returns the input that wasn't reached initially. This method returns the rest of the current line, excluding any line separator at the end of the line.


2 Answers

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.

like image 154
ramesh Avatar answered Oct 07 '22 18:10

ramesh


You can do this:

Scanner s = new Scanner(System.in);
while (s.hasNextInt()) {
    A[i] = s.nextInt();
    i++;
}
like image 20
Ted Hopp Avatar answered Oct 07 '22 20:10

Ted Hopp