简体   繁体   English

Java无法读取字符是换行符

[英]Java can't read that the character is a new line

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

I am reading an input text file that has three blank lines. 我正在读取具有三个空白行的输入文本文件。 x reads character by character. x逐个字符读取。 x is equal to a new line so it suppose to go into the while loop but it does not. x等于新行,因此它假定进入while循环,但不行。 I debugged the code and printed out to check if x is holding a new line. 我调试了代码并打印出来,以检查x是否持有新行。 It prints out x= 13, x = 10, x = 10. In all three of these cases, it skips the while loop. 它打印出x = 13,x = 10,x =10。在所有这三种情况下,它都会跳过while循环。

Another method I tried: 我尝试过的另一种方法:

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

When I write it in its own while loop it will enter the loop the second time (x = 10) but come back out the third time when x = 10. Which isn't suppose to happen it should stay in the loop until it hits the end of file (x = -1). 当我用自己的while循环编写它时,它将第二次进入循环(x = 10),但是当x = 10时将第三次退出循环。这不应该发生,它应该一直停留在循环中,直到命中为止文件末尾(x = -1)。

I also tried Character.toString((char) nextChar) == "\\r\\n" but that has the same result as the first one. 我也尝试过Character.toString((char)nextChar)==“ \\ r \\ n”,但结果与第一个相同。

What am I doing wrong? 我究竟做错了什么?

I am reading an input text file that has three blank lines. 我正在读取具有三个空白行的输入文本文件。

The better way is read line by line and check each line whether it is empty or not. 更好的方法是逐行读取并检查每行是否为空。

Sample code: 样例代码:

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

"Blank line" may be a bit vague thing. “空白行”可能有点含糊。 Your "\\r\\n" attempt is close to the root cause of your issue (just strings should be compared via .equals instead of ==). 您的“ \\ r \\ n”尝试接近问题的根本原因(只是应该通过.equals而不是==来比较字符串)。

Another solution could be to create a proper input file where a new line is indeed just "\\n" instead of "\\r\\n" (ascii codes 13, 10). 另一种解决方案是创建一个正确的输入文件,其中的新行实际上只是“ \\ n”而不是“ \\ r \\ n”(ASCII码13、10)。

You could attempt to use something like 您可以尝试使用类似

while (Character.isWhitespace(x){
    // skip
}

The documentation for Character.isWhitespace(char) is here . Character.isWhitespace(char)的文档在此处

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

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