I read a normal text file with the following term:
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();
The content of the file could be as follows:
This is a test text\nline break before\n\nantoher line break
Now my problem is, if I set this text into a TextArea, the text get just printed out as is:
This is a test text\nline break before\n\nantoher line break
Just if I set the text the following way:
textArea.setValue("This is a test text\nline break before\n\nantoher line break");
the line breaks are printed out.
What can I do the preserver the "\\n" line breaks while reading a string from a file?
You're losing the line breaks as a result of readAllLines
. You can manually add the line break in the append call. You may or may not want to add one to the last line.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.