运行java程序时出现FileNotFoundException错误

我在运行代码时收到FileNotFoundException。 我的filname是filecontent.java …

定义:我想创建一个包含4个TextFields和4个TextAreas的程序。 如果在TextField中键入文件的名称,则其内容应显示在相应的TextArea中。

错误:

例外e:java.io.FileNotFoundException:

我的代码:

import java.awt.*; import java.awt.event.*; import java.io.*; class filecontent extends Frame implements ActionListener { TextField t[]=new TextField[4]; TextArea ta[]=new TextArea[4]; Button submit,exit=new Button("Exit"); Panel p1; filecontent() { setGUI(); setRegister(); try{ showfile(); } catch(IOException ioe) { System.out.println("Exception e : "+ioe); } setTitle("FileData"); setVisible(true); setSize(300,300); setLocation(500,200); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { System.exit(0); } }); } void setGUI() { p1=new Panel(); p1.setLayout(new GridLayout(5,4,10,10)); for(int i=0;i<4;i++) { t[i]=new TextField(10); ta[i]=new TextArea(); p1.add(t[i]); p1.add(ta[i]); } submit=new Button("Submit"); p1.add(submit); p1.add(exit); } void setRegister() { submit.addActionListener(this); exit.addActionListener(this); } void showfile() throws java.io.IOException { FileReader fin[]=new FileReader[4]; FileReader fn=new FileReader("filecontent.java"); BufferedReader br[]=new BufferedReader[4]; for(int i=0;i<4;i++) { fin[i]=new FileReader(t[i].getText()); } int cnt=1; String s; fn=fin[0]; br[0]=new BufferedReader(fn); while(cnt<=4) { if((s=br[cnt-1].readLine())!=null) { ta[cnt-1].append(s+""); } else { fin[cnt-1].close(); cnt++; fn=fin[cnt-1]; br[cnt-1]=new BufferedReader(fn); ta[cnt-1].setText(""); } } } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==submit) { try{ showfile(); } catch(IOException ioe) { System.out.println("Exception e"+ioe); } } else if(ae.getSource()==exit) { System.exit(0); } } public static void main(String ar[]) { new filecontent(); } } 

您没有NullPointerException。 你有一个FileNotFoundException。 正如此例外的名称所说,这是因为找不到您尝试打开的文件。

失败的第一个文件访问是这一个:

 FileReader fn=new FileReader("filecontent.java"); 

如果您的java文件位于项目的src(或任何其他)文件夹中,则必须添加该文件夹。 例如src/filecontent.java

其他一些说明:

  • 按照惯例,java类名称以大写字母开头
  • 您的变量名称t, ta, p1, etc.可能会令人困惑。 为什么不使用textFields, textAreas, panel
  • 我想你会遇到这行中的ArrayIndexOutOfBoundsException while(cnt<=4) 。 数组索引以0开头,以n - 1结尾(在您的情况下= 3)
  • 它可以帮助debuging打印出catch块中的stacktrace: ioe.printStackTrace() 。 这将为您提供代码失败的确切行号

您的例外可能来自此行

 FileReader fn=new FileReader("filecontent.java"); 

我认为你应该使用完整路径,而不仅仅是文件名。

首先,为什么不使用FileDialog而不是textField作为文件。 其次,您正在使用相对路径,以便您的程序工作,文件filecontent.java必须与.class文件位于同一位置

在java中读取文件时,filepath的语法因系统而异。 因此,您应该根据您使用的操作系统应用路径。 同样对于您的代码,文件filecontent.java应该位于同一目录中。

根据您的评论,答案是该文件在资源管理器中显示为a.txt但实际上是a.txt.txt在资源a.txt.txt显示文件扩展名可以避免此问题/混淆。


当您使用文件路径时,它相对于工作目录,即运行应用程序的位置。 不是可以找到源代码的地方。 如果您不知道工作目录是什么,则应使用完整路径名。