我有一个 JTextArea(又名“注释”),用户可以在其中键入文本并以他们希望的任何格式设置间距。然后,该字符串与其他字符串一起存储在一个文件中,以便稍后读取。 “notes”字符串应稍后读入,并以与最初保存时相同的格式放回到 JTextArea 中。
如果您有 2 个文本区域,这样做将传输正确的格式:
JTextArea text1 = new JTextArea();
JTextArea text2 = new JTextArea();
text2.setText(text1.getText);
但是,写入文件是不同的,因为 in.next();
读取一个字符串,而不是整个文本区域的值。
从文本文件中读取/多个字符串后,如何保持正确的格式?
编辑:该文件看起来像这样:
String1
String2
some_long_string
12345
foobar
This string was taken from the JTextArea mentioned above. Imagine that this is all one String and has a lot of whitespace in it.
最佳答案
JTextArea 中的文本可以包含换行符,因此您必须在文件中写入一些内容来解释这一点。
一种方法是编写不太可能出现在 JTextArea 文本中的分隔符字符串:
String1
String2
some_long_string
12345
foobar
*** BEGIN JTEXTAREA TEXT ***
This string was taken from the JTextArea.
It contains multiple lines.
*** END JTEXTAREA TEXT ***
另一种方法是转义换行符。您可以使用 URLEncoder 和 URLDecoder,只要您不介意文件中的文本不太容易阅读:
String1
String2
some_long_string
12345
foobar
This+string+was+taken+from+the+JTextArea.%0AIt+contains+multiple+lines.
关于java - 文件将多行读取到一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18971980/