我不確定問題產生於哪裏。我有兩個類,一個叫做testFriends類,另一個叫做GUIapp類。在每個類中,我的目標是導入文件以供使用。在testFriends類中,我在主要方法中導入文件,解析它並且一切都很好。在我的GUIapp類中,我試着做同樣的事情,但將其導入構造函數方法中,並告訴我該文件不存在。這兩個文件的類駐留在同一個src文件夾,我使用:在Java構造函數中導入文本文件
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)
請指定啓動applet的方式/位置。根據您的答案,您可能需要閱讀[Applets可以做什麼和不可以做什麼](http://docs.oracle.com/javase/tutorial/deployment/applet/security.html)。 – 2013-02-15 22:10:30
這是我第一次做GUI設計。我通過調用createStuff方法的「init」方法來初始化applet。 – user1234440 2013-02-15 22:11:36
不,我的意思是使用什麼工具來啓動小程序?如果您在瀏覽器中查看它,請務必查看我上面提到的鏈接。無論如何,你可能都想查看它。 – 2013-02-15 22:13:07