我的问题是,当我使用这段代码时,我只得到包含我所要求的单词的最后一行文字,我怎样才能获得包含我要求的特定单词的所有行,然后将它们妥善存储到jTextArea
中?
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) !=null) {
if(line.contains("Win")){
jTextArea1.setText(line);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
jTextArea1.setText("sup");
}
问题是您正在使用方法setText()。每次调用setText()时,它都会替换文本区域。你要做的是附加所以你需要打电话:jTextArea.append(word)
一种方法是将String保存到List
List<String> words = new ArrayList<>();
...
if (line.contains("Win")) {
words.add(line);
}
...
String output = StringUtils.join(words, "\n");
jTextArea1.setText(output);
最后几行将使用新行标记连接ArrayList中的每个单词以加入单词。