简体   繁体   English

如何使用Java中的BufferedReader读取文件结尾(EOF)?

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

I have problem with reading the input until EOF in Java . 我在阅读输入时EOF问题,直到Java EOF 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. 但是,我使用Java进行编码,当我输入两个数字时,将打印单个输出。 I want single input and print single output each line (terminate EOF ) using BufferedReader in Java. 我希望使用Java中的BufferedReader单行输入并打印单行输出(终止EOF )。

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());
}

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 所以尝试从字符串中获取bigint

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

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

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

see related post string to bigint 看到相关的帖子字符串到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 javadocs

With text files, maybe the EOF is -1 when using BufferReader.read(), char by char. 使用文本文件时,使用BufferReader.read()时,EOF可能为-1,char为char。 I made a test with BufferReader.readLine()!=null and it worked properly. 我用BufferReader.readLine()!= null做了一个测试,它运行正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM