如何将文本文件内容导入Java应用程序中的JTextArea?

mwd*_*dar 1 java import file-io swing jtextarea

如何使用JFileChooser将Text文件内容导入Java应用程序中的JTextArea?

Mav*_*rik 6

应该是类似下面的代码:

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null); //replace null with your swing container
File file;
if(returnVal == JFileChooser.APPROVE_OPTION)     
  file = chooser.getSelectedFile();    
}

JTextArea text = new JTextArea();
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line != null){
  text.append(line + "\n");
  line = in.readLine();
}
Run Code Online (Sandbox Code Playgroud)

卢卡

  • -1,是的,我知道这有效.但我倾向于投票重新制定解决方案.所有文本组件都支持应该使用的read(...)方法. (2认同)
  • @camickr 我同意我们不应该重新发明轮子……无论如何我没有找到你的提议,我不明白你为什么只投了我的提议,当有其他两个回答提出同样的方法而不发布时编码。 (2认同)
  • 我的建议是使用read(..)方法.我投了票,因为这是接受的答案,我不希望搜索论坛的人找到这个答案来使用它. (2认同)