Java无法读取该字符是换行符

标签 java loops while-loop char newline

if (first == true) {
    x = input.read(); // input is a Reader
    nextCharacter = input.read();
    first = false;
}
else {
    x = nextCharacter;
    nextCharacter = input.read();
    charPosition++;
}

while (x == ' ' || x == '\n') {
    if (x == ' ') {
        x = nextCharacter;
    }
    else {
        x = nextCharacter;
    }
}

我正在读取一个包含三个空行的输入文本文件。 x 逐个字符地读取。 x 等于新行,因此它应该进入 while 循环,但事实并非如此。我调试了代码并打印出来以检查 x 是否持有新行。它打印出 x= 13、x = 10、x = 10。在所有这三种情况下,它都会跳过 while 循环。

我尝试过的另一种方法:

while(x == '\n') {
    System.out.println("entered");
    x = nextCharacter;
}

当我将它写在自己的 while 循环中时,它将第二次进入循环(x = 10),但在第三次 x = 10 时返回。这是不应该发生的,它应该留在循环中直到到达文件末尾 (x = -1)。

我还尝试了Character.toString((char) nextChar) == "\r\n"但结果与第一个相同。

我做错了什么?

最佳答案

I am reading an input text file that has three blank lines.

更好的方法是逐行读取并检查每一行是否为空。

示例代码:

    BufferedReader reader = new BufferedReader(new FileReader(new File("resources/abc.txt")));

    String line = null;
    while ((line = reader.readLine()) != null) {
        if (!line.isEmpty()) {
            System.out.println(line);
            // do whatever you want to do with char array if needed
            // char[] arr=line.toCharArray();
        }
    }
    reader.close();

关于Java无法读取该字符是换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048655/

相关文章:

c - 如何修复段错误?

javascript - 如何通过对象数组运行 forEach 并为具有空字符串的对象属性设置值?

bash - "while read LINE do"和 grep 问题

java - rs.getInt(1) 无法正常工作

java - Runtime.availableProcessors : what is it going to return?

java - 如何修复异常 : Failed to instantiate SLF4J LoggerFactory?

c - C语言中的while循环

java - 如何停止 swt 上的按键事件传播

excel - 总是被踢出潜艇?

java - 为什么 for 循环索引不能正常工作?