包含换行符的文件中的字符串未在 TextArea 中设置

String from file containing line breaks are not set in TextArea

我阅读了一个包含以下术语的普通文本文件:

    StringBuilder sb = new StringBuilder();
    for (String line : Files.readAllLines(file.toPath())) // The function Files.readAllLines reads the file using standard UTF-8 encoding
    {
      sb.append(line);
    }
    return sb.toString();

文件内容可能如下:

This is a test text\nline break before\n\nantoher line break

现在我的问题是,如果我将此文本设置到 TextArea 中,文本将按原样打印出来:

This is a test text\nline break before\n\nantoher line break

如果我按以下方式设置文本:

textArea.setValue("This is a test text\nline break before\n\nantoher line break");

打印出换行符。

在从文件中读取字符串时如何保留“\n”换行符?

由于 readAllLines,您正在丢失换行符。您可以在追加调用中手动添加换行符。您可能想也可能不想在最后一行添加一个。

StringBuilder sb = new StringBuilder();
for (String line : Files.readAllLines(file.toPath())) // The function Files.readAllLines reads the file using standard UTF-8 encoding
{
  sb.append(line).append('\n');
}
return sb.toString();