How to read until end of file (EOF) using BufferedReader in Java?

meisyal picture meisyal · Aug 1, 2013 · Viewed 140.2k times · Source

I have problem with reading the input until EOF in Java. In here, there are single input and the output consider the input each line.

Example:

input:

1
2
3
4
5

output:

0 
1
0
1
0

But, I have coded using Java, the single output will printed when I was entering two numbers. I want single input and print single output each line (terminate EOF) using BufferedReader in Java.

This is my code:

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringBuffer pr = new StringBuffer("");

String str = "";
while((str=input.readLine())!=null && str.length()!=0) {
    BigInteger n = new BigInteger(input.readLine());
}

Answer

a question picture a question · Aug 1, 2013

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs