一次添加一行到一个字符串 [英] Add a line at a time to a String
问题描述
我有这个程序可以让你打开一个文件,并使用下面的代码一次性读入一个 JTextArea
>
try {
String fileContents = new Scanner(new File(fileName))。useDelimiter(\\Z)。
} catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
这个工作。但我的问题是我怎么能读取到我的 fileContents
字符串,并仍然有它添加在换行符每次我换行符
以下是我所拥有的内容,但是这将它放在我的textArea中:
try {
Scanner contentsTextFile = new Scanner(new File(fileName));
while(contentsTextFile.hasNext()){
fileContents = contentsTextFile.useDelimiter(\r\\\
| \\\
)。nextLine();
$ b $ catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
我想要看到的是这行文本使用一个只能读取分隔符的新行一行一行,而不是整个文件。
有人可以帮忙吗?
您可以使用 BufferedReader
逐行读取文件,并使用 append()
每行读取的 JTextArea
方法。为了方便起见,将 JTextArea
包装在适当大小的 JScrollPane
中,如此处。如果您预计有任何延迟,请使用 SwingWorker
在后台读取,并在 process()中调用 append()
>。 BufferedReader in = new BufferedReader(new FileReader(fileName));
String s; ((s = in.readLine())!= null){
myTextArea.append(s +\\\
);
}
I have this program that lets you open a file and it reads it in to a JTextArea
all at once using the following code:
try{
String fileContents = new Scanner(new File(fileName)).useDelimiter("\\Z").next();
}catch(FileNotFoundException ex){
ex.printStackTrace();
}
myTextArea.setText(fileContents);
and this works. But my question is how can I read this into my fileContents
string and still have it add in the line breaks every time I get a new-line character?
Here is what I have, but this puts it all in one line in my textArea:
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);
What I would like to see is this line of text get a new line using a delimiter that only reads one line at a time instead of the entire file.
Can someone help?
解决方案 You can read a file line-by-line using a BufferedReader
and use the append()
method of JTextArea
for each line read. For convenience, wrap the JTextArea
in a suitably sized JScrollPane
, as shown here. If you anticipate any latency, use a SwingWorker
to read in the background, and call append()
in process()
.
BufferedReader in = new BufferedReader(new FileReader(fileName));
String s;
while ((s = in.readLine()) != null) {
myTextArea.append(s + "\n");
}
这篇关于一次添加一行到一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!