gpt4 book ai didi

java - 为什么代码片段无法检测到行尾

转载 作者:行者123 更新时间:2023-12-02 00:38:31 26 4
gpt4 key购买 nike

FileReader reader = new FileReader("d:\\UnderTest\\AVS\\tester.txt");
char ch;
int x;
while( ( x = reader.read() ) != -1 ) {
// I use the following statement to detect EOL
if( Character.toString((char)x) == System.getProperty("line.separator") ) {
System.out.println("new line encountered !");
} System.out.print( (char)x );
}

在此代码中,if 语句永远不会起作用,尽管在 tester.txt 中有 2 个句子写在新行上。为什么 ?

最佳答案

正如一些人提到的,系统属性 line.separator 可能会返回多个字符,例如在 Windows 上,它是 \r\n

根据您的用例,您可能最好使用 BufferedReader::readLine()直接读取整行并避免执行手动比较。

关于java - 为什么代码片段无法检测到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7048757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com