有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中读取文本文件直到EOL

我正在读一个文本文件

hello James!
How are you today!

我想读取字符串中的每个字符,直到找到EOL字符。因为我使用的是windows,其中有/n/r代表EOL字符。我如何写一个条件来遍历字符串的所有字符,并逐个打印它们,直到它达到EOL(/n/r)为止

int readedValue;

do
{   
    while((readedValue = bufferReader.read()) != 10)
   {
    //readedValue = bufferReader.read();
    char ch = (char) readedValue;
    System.out.print(ch);
   } 

}
while ((readedValue = bufferReader.read()) != -1);

当我现在读到这个文件时,我的名字是hello James!你今天好

我不知道该怎么做。我可以通过什么修改来获得完整的文本


共 (2) 个答案

  1. # 1 楼答案

    你的问题是关于魔法数字

    如果charAt(21)!='\n'amp&;查拉特(22)!='\r'

    这两个整数应在循环内增加

    charAt(i)!='\n' && charAt(i+1)!='\r'
    ::inside loop
      i++
    
  2. # 2 楼答案

    正如人们所注意到的,readline()方法读取下一行分隔符,并返回移除分隔符的行。所以你对'\n''\r'line中的测试不可能评估为true

    但是,当您输出line字符串1时,可以很容易地添加额外的行尾

    1——也就是说,除非您实际上需要保留与输入流中完全相同的行尾序列字符

    你问:

    Instead of using readline(), Is there any way i can use buffer reader to read each character and print them?

    是的,当然。read()方法返回一个字符或-1以指示EOF。所以:

        int ch = br.read();
        while (ch != -1) {
           System.out.print((char) ch);
           ch = br.read();
        }