【问题标题】:How to read until end of file (EOF) using BufferedReader in Java?如何在 Java 中使用 BufferedReader 读取文件末尾 (EOF)?
【发布时间】:2013-08-02 05:21:45
【问题描述】:

我在阅读 Java 中的 EOF 之前的输入时遇到问题。在这里,有单个输入,输出考虑每一行的输入。

示例:

输入:

1
2
3
4
5

输出:

0 
1
0
1
0

但是,我使用 Java 编码,当我输入两个数字时,将打印单个输出。我想要在 Java 中使用 BufferedReader 进行单输入并在每行打印单输出(终止 EOF)。

这是我的代码:

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

【问题讨论】:

  • 你能粘贴你的代码来帮助你吗?
  • 可能是br.readLine() != null !!!
  • 粘贴你的代码?你这样做是为了什么
  • @AndriasMeisyal 目前还不清楚。你想要什么类型的输入,输出应该是什么?如果将 1 2 3 作为输入,则无法将其转换为整数,因为 1 2 3 之间存在空格而无需修改。
  • 是的,你是对的。但是,对不起,每行都是单输入..

标签: java io bufferedreader


【解决方案1】:

对于文本文件,使用 BufferReader.read() 时,EOF 可能为 -1,逐个字符。 我用 BufferReader.readLine()!=null 做了一个测试,它工作正常。

【讨论】:

    【解决方案2】:

    你正在消耗一条线,它被丢弃了

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

    并在

    处阅读 bigint
    BigInteger n = new BigInteger(input.readLine());
    

    所以尝试从被读取为的字符串中获取 bigint

    BigInteger n = new BigInteger(str);
    
       Constructor used: BigInteger(String val)
    

    也将while((str=input.readLine())!=null && str.length()!=0) 更改为

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

    查看相关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 
    

    javadocs

    【讨论】:

    • 天啊。谢谢,它有效,我可以了解更多关于你告诉我的台词。谢谢,再次感谢你,@一个问题
    • 如果我的文件包含null 作为字符串会发生什么?我无法读取完整文件,这是一个原因吗?
    • @astuter null 是一个 java 关键字。 "null" 是一个字符串。看出区别了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多