我读取了包含以下术语的普通文本文件:
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();
关于java - 包含换行符的文件中的字符串未在 TextArea 中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36688188/