在Java GUI中读取txt文件

我想要做的就是显示txt文件的全部内容。 我该怎么做呢? 我假设我将JLabel的文本设置为包含整个文件的字符串,但是如何将整个文件转换为字符串? 此外,txt文件是否在Eclipse的src文件夹中?

此代码用于在Jtext区域中显示所选文件内容

static void readin(String fn, JTextComponent pane) { try { FileReader fr = new FileReader(fn); pane.read(fr, null); fr.close(); } catch (IOException e) { System.err.println(e); } } 

选择文件

  String cwd = System.getProperty("user.dir"); final JFileChooser jfc = new JFileChooser(cwd); JButton filebutton = new JButton("Choose"); filebutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (jfc.showOpenDialog(frame) !=JFileChooser.APPROVE_OPTION) return; File f = jfc.getSelectedFile(); readin(f.toString(), textpane); SwingUtilities.invokeLater(new Runnable() { public void run() { frame.setCursor(Cursor. getPredefinedCursor( Cursor.DEFAULT_CURSOR)); } }); } }); 

我想要做的就是显示txt文件的全部内容。 我该怎么做呢? 我假设我将JLabel的文本设置为包含整个文件的字符串,但如何将整个文件转换为字符串?

你最好使用JTextArea来做到这一点。 您还可以查看read()方法。

txt文件是否在Eclipse的src文件夹中?

不。 您可以从任何位置读取文件。 “阅读,编写和创建文件”教程将是一个很好的起点

  • 在项目的工作文件夹中创建文本文件
  • 逐行读取您的文本文件
  • 将行内容存储在stringBuilder变量中
  • 然后将下一行内容附加到stringBuilder变量
  • 然后将StringBuilder变量的内容分配给JLabel的text属性

但是将整个文件的数据存储到JLabel ,使用JTextArea或任何其他文本容器并不是一个好主意。

像这样读取你的文件:

 BufferedReader br = new BufferedReader(new FileReader("file.txt")); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } 

现在为JLabelJTextArea分配所有JTextArea

 JLabel1.text=everything; 
  1. 使用java.io打开文件流。
  2. 按行或字节从文件中读取内容。
  3. 将内容附加到StringBuilderStringBuffer
  4. StringBuilderStringBuffer设置为JLable.text

但我建议使用JTextArea ..

您不需要将此文件放在src文件夹中。