我不确定问题是从哪里产生的。我有两个类,一个称为 testFriends 类,另一个称为 GUIapp 类。在每个类中,我的目标是导入文件以供使用。在 testFriends 类中,我在 main 方法中导入文件,它解析它并且一切正常。在我的 GUIapp 类中,我尝试做同样的事情,但是在构造函数方法中导入它,它告诉我文件不存在。这两个文件类都位于同一个 src 文件夹中,我正在使用:
BufferedReader in = new BufferedReader(new FileReader(inputFile));
其中 inputFile 只是一个字符串“friends.txt”。
这是两个类:
//This class works
public class temp {
public static void main(String[] args) throws ParseException {
try {
System.out.println("hey");
BufferedReader in = new BufferedReader(new FileReader("friends.txt")); //create string buffer for reading
String line = in.readLine(); //reading first line
System.out.println(line);
} catch (IOException e) {
System.out.println("Fail Import.");
}
}
}
//////////The one below doesn't...
public class GUIapp extends JApplet{
//** PANEL **//
private JPanel outerPanel;
//** Button **//
private JButton button1;
/*
* Constructor for Getting all the friends set up
*/
public GUIapp() throws ParseException, FileNotFoundException{
BufferedReader in = new BufferedReader(new FileReader("friends.txt"));//Error Line
}
/*
* Create Stuff
*/
public void createStuff() {
outerPanel = new JPanel(); //create outer panel
button1 = new JButton("Click Me");
outerPanel.add(button1,BorderLayout.SOUTH);
}
/*
* Initialize Stuff
*/
public void init(){
createStuff(); //initialize create stuff
this.add (outerPanel);
}
}
任何想法为什么当两者都在同一个目录中工作时,一个可以读取而另一个不能?
谢谢,
编辑:下面是我运行 GUIapp 类时抛出的异常:
java.io.FileNotFoundException: friends.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at java.io.FileReader.<init>(FileReader.java:41)
at GUIapp.<init>(GUIapp.java:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:807)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
at sun.applet.AppletPanel.run(AppletPanel.java:368)
at java.lang.Thread.run(Thread.java:680)