gpt4 book ai didi

java - 运行java程序时出现FileNotFoundException错误

转载 作者:行者123 更新时间:2023-12-01 15:37:02 26 4
gpt4 key购买 nike

我在运行代码时收到 FileNotFoundException。我的文件名是 filecontent.java...

定义:我想创建一个具有 4 个文本字段和 4 个文本区域的程序。如果在 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)
  • 它可以帮助调试打印出 catch block 中的堆栈跟踪:ioe.printStackTrace() 。这将为您提供代码失败的确切行号

关于java - 运行java程序时出现FileNotFoundException错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8711210/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com