我有这个程序,可以让你打开一个文件并将其读入一个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);
我希望看到的是,这行文本使用分隔符获得一个新行,该分隔符一次只读取一行而不是整个文件。
有人可以帮忙吗?
您可以使用以下命令逐行读取文件BufferedReader
并使用append()
的方法JTextArea
对于读取的每一行。为了方便起见,将其包裹起来JTextArea
在一个合适大小的JScrollPane
, 如图所示here https://stackoverflow.com/a/14011536/230513。如果您预计会有任何延迟,请使用SwingWorker http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html在后台读取并调用append()
in process()
.
BufferedReader in = new BufferedReader(new FileReader(fileName));
String s;
while ((s = in.readLine()) != null) {
myTextArea.append(s + "\n");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)