在Java GUI中读取txt文件 [英] Reading a txt file in a Java GUI
本文介绍了在Java GUI中读取txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
这段代码在你的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;
文件f = jfc.getSelectedFile();
$ b $ readin(f.toString(),textpane) ;
SwingUtilities.invokeLater(new Runnable(){
public void run(){
frame.setCursor(Cursor。
getPredefinedCursor(
Cursor。 DEFAULT_CURSOR));
}
});
}
});
All I want to do is display the entire contents of a txt file. How would I go about doing this? I'm assuming that I will set the text of a JLabel to be a string that contains the entire file, but how do I get the entire file into a string? Also, does the txt file go in the src folder in Eclipse?
解决方案 This code to display the selected file contents in you Jtext area
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);
}
}
To choose the file
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));
}
});
}
});
这篇关于在Java GUI中读取txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文