import java.awt.*;
import java.io.*;
import javax.swing.*;
//import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.filechooser.FileFilter;
public class test extends JFrame
{
static int result;
static JFileChooser jf;
JButton jbt;
public test()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout(1));
jf=new JFileChooser();
jbt=new JButton("打开文件");
jf.setFileFilter(new FFT());
jbt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
result=jf.showOpenDialog(null);
}
}
);
cp.add(jbt);
setSize(400,400);
setVisible(true);
}
public static void main(String[]args)throws IOException
{
File file=null;
String name;
test ap=new test();
ap.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if(result == JFileChooser.APPROVE_OPTION)
{
file = jf.getSelectedFile();
FileInputStream f=new FileInputStream(file);
int n=f.available();
byte[] b=new byte[n];
while(f.read(b)==-1)
return;
String str=new String(b);
System.out.print(str);
f.close();
}
}
}
class FFT extends FileFilter
{
public boolean accept(File f)
{
if(f.getPath().endsWith(".txt")||f.isDirectory())
return true;
else
return false;
}
public String getDescription()
{
return "txt文件";
}
}
----------------解决方案--------------------------------------------------------
正在看书 比较着急
import java.awt.*;
import java.io.*;
import javax.swing.*;
//import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.filechooser.FileFilter;
public class test extends JFrame
{
static int result;
static JFileChooser jf;
JButton jbt;
public test()
{
Container cp=getContentPane();
cp.setLayout(new FlowLayout(1));
jf=new JFileChooser();
jbt=new JButton(\"打开文件\");
jf.setFileFilter(new FFT());
jbt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
result=jf.showOpenDialog(null);
File file=null;
String name;
if(result == JFileChooser.APPROVE_OPTION)
{
file = jf.getSelectedFile();
try{
FileInputStream f=new FileInputStream(file);
int n=f.available();
byte[] b=new byte[n];
while(f.read(b)==-1)
return;
String str=new String(b);
System.out.print(str);
f.close();
}catch(FileNotFoundException eee){
System.out.print(\"文件不存在\");
}catch(IOException ee){
}
}
}
}
);
cp.add(jbt);
setSize(400,400);
setVisible(true);
}
public static void main(String[]args)
{
test ap=new test();
ap.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class FFT extends FileFilter
{
public boolean accept(File f)
{
if(f.getPath().endsWith(\".txt\")||f.isDirectory())
return true;
else
return false;
}
public String getDescription()
{
return \"txt文件\";
}
}
你的程序在这段之前file还是null的 除非把它搬到处理触发事件的方法里面去
if(result == JFileChooser.APPROVE_OPTION)
{
file = jf.getSelectedFile();
FileInputStream f=new FileInputStream(file);
int n=f.available();
byte[] b=new byte[n];
while(f.read(b)==-1)
return;
String str=new String(b);
System.out.print(str);
f.close();
}
----------------解决方案--------------------------------------------------------