从带有 java.util.Scanner 的文件中读取字符串并使用换行符作为分隔符时,字符串的行为很奇怪

Strings act weirdly when reading them from a file with the java.util.Scanner and using linebreaks as delimiter

我尝试使用 java.util.Scanner 从文件中读取数据。当我尝试使用 \n 作为分隔符时,当我尝试向它们添加更多文本时,生成的字符串会做出奇怪的反应。

我有一个名为 "test.txt" 的文件并尝试从中读取数据。然后我想向每个字符串添加更多文本,类似于打印 Hello World!:

的方式
String helloWorld = "Hello "+"World!";
System.out.println(helloWorld);.

我尝试将数据与 + 结合,我尝试了 += 并且我尝试了 String.concat(),这以前对我有用,现在通常仍然有效。

我还尝试使用不同的分隔符,或者根本不使用分隔符,这两种方法都按我的预期工作,但我需要在换行符处分隔字符串。

最小可重现示例的 test.txt 文件包含此文本(每行末尾有一个 space):

zero:
one:
two:
three:

void minimalReproducibleExample() throws Exception {  //May throw an exception if the test.txt file can't be found

    String[] data = new String[4];

    java.io.File file = new java.io.File("test.txt");
    java.util.Scanner scanner = new java.util.Scanner(file).useDelimiter("\n");

    for (int i=0;i<4;i++) {
        data[i] = scanner.next();     //read the next line
        data[i] += i;                 //add a number at the end of the String
        System.out.println(data[i]);  //print the String with the number
    }

    scanner.close();
}

我希望这段代码打印出这些行:

zero: 0
one: 1
two: 2
three: 3

我得到的是这个输出:

0ero:
1ne:
2wo:
three: 3

为什么我在使用 \n 作为分隔符时没有得到预期的输出?

test.txt 最有可能使用 Windows end of line representation \r\n which results in carriage return \r 在阅读后仍然存在于 String 中。

确保 test.txt 使用 \n 作为行分隔符或在 Scanner.useDelimiter().

中使用 Windows \r\n

问题很可能与错误的分隔符有关。如果使用 Windows 10,则新行分隔符为 \r\n.

只是 platform-independent 使用 System.getProperty("line.separator") 而不是硬编码 \n