Java 扫描仪在读取行时是否可以包含 '\n' ?

Is there a way for Java Scanner to include '\n' when it is reading lines?

有什么方法可以让 java.util.Scanner 在读取文件时包含换行符?

这是我的代码:

File myFile = new File("file.txt");
Scanner myReader = new Scanner(myFile);
String content = "";
while(myReader.hasNextLine()) {

    content += myReader.nextLine();
}
System.out.println(content);
myReader.close();

当它从文件中读取时,它不包括“\n”或任何新行。有人知道怎么做吗?

谢谢

When it reads from the file, it doesn't include '\n' or any new lines. Does anyone know how to do this?

您可以按如下方式显式添加新行:

while(myReader.hasNextLine()) {
    content += myReader.nextLine() + "\n";
}

我还建议您使用 StringBuilder 而不是 String 来循环追加。

StringBuilder content = new StringBuilder();
while (myReader.hasNextLine()) {
    content.append(myReader.nextLine()).append(System.lineSeparator());
    // or the following
    // content.append(myReader.nextLine()).append('\n');
}

查看 StringBuilder vs String concatenation in toString() in Java 了解更多信息。

如果您只想读取行和行终止符,您可以通过更改 Scanner.next() 的行为来实现。如果您 运行 以下内容,它将把行和新行终止符作为一个单元。

  • \z 是一个正则表达式指令,表示包含行终止符。
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\z");
for (int i = 0; i < 5; i++) {
    String line = scan.next();
    System.out.println(line + "on next line");
}

要从文件中读取,试试这个。

try {
    Scanner scan = new Scanner(new File("f:/Datafile.txt"));
    scan.useDelimiter("\z");
    while (scan.hasNextLine()) {
        String line = scan.next();
        System.out.print(line);
    }
} catch (FileNotFoundException fe) {
    fe.printStackTrace();
}