//这是我编绎的一个浏览文件的程序,但有一处错误我怎么也不会改,望高手不吝指教
/*
 * Created on 2007-7-1
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;public class FileViewer extends JFrame implements ActionListener{
private JButton jbtView=new JButton("View");

private JTextField jtfFilename=new JTextField(12);

private JTextArea jtaFile=new JTextArea(); public FileViewer() {
// TODO Auto-generated constructor stub
Panel p=new Panel();
p.setLayout(new BorderLayout());
p.add(new Label("Filename"),BorderLayout.WEST);
p.add(jtfFilename,BorderLayout.CENTER);
p.add(jbtView,BorderLayout.SOUTH);

JScrollPane jsp=new JScrollPane(jtaFile);

getContentPane().add(jsp,BorderLayout.CENTER);
getContentPane().add(p,BorderLayout.SOUTH);

jbtView.addActionListener(this);

}

public void actionPerformed(ActionEvent e){
if(e.getSource()==jbtView)
showFile();
}

private void showFile(){
BufferedReader input=null;
String filename=jtfFilename.getText().trim();
String inLine;
try{
input=new BufferedReader(new FileReader(filename));
while((inLine=input.readLine())!=null){ //错误就在这一行
jtaFile.append(inLine+'\n');
}
}
catch(FileNotFoundException ex){
System.out.println("File not found:"+filename);
}
finally{
try{
if(input!=null)input.close();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
} /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
FileViewer frame=new FileViewer();
frame.setTitle("FileViewer");
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); }}

解决方案 »

  1.   

    因为你少捕获了一个异常,在你标记错误的那个行所在的try-catch块中增加一个catch块,最后如下:
    try{
        input=new BufferedReader(new FileReader(filename));
        while((inLine=input.readLine())!=null){ //错误就在这一行(没处理度数据时可能出现的IOException )
       jtaFile.append(inLine+'\n');
    }
    }
    catch(FileNotFoundException ex){
        System.out.println("File not found:"+filename);
    }
    catch(IOException ex){
        System.out.println("File read Error:"+filename);
    }