java每次向字符串添加一行
我有一个程序,可以让你打开一个文件,然后用下面的代码一次把它读入一个JTextArea
:
try{
String fileContents = new Scanner(new File(fileName)).useDelimiter("\\Z").next();
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
这是有效的。但我的问题是,如何将其读入我的fileContents
字符串中,并在每次获得新行字符时仍将其添加到换行符中
这是我所拥有的,但这将它全部放在我的文本区域的一行中:
try{
Scanner contentsTextFile = new Scanner(new File(fileName));
while(contentsTextFile.hasNext()){
fileContents = contentsTextFile.useDelimiter("\r\n|\n").nextLine();
}
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
我想看到的是,这行文本使用分隔符获得一个新行,该分隔符一次只读取一行,而不是整个文件
有人能帮忙吗
# 1 楼答案
最简单的方法是使用^{} ,其中:
# 2 楼答案
您可以使用} 在后台读取,并在
BufferedReader
逐行读取文件,并对每一行读取使用JTextArea
的append()
方法。为方便起见,将JTextArea
包装成大小合适的JScrollPane
,如图here。如果您预期任何延迟,请使用^{process()
中调用append()