2012-06-16 114 views
0
import java.io.*; 
import java.util.Scanner; 
public class Test { 
    /** 
    * @param args 
    */ 
    public static void main(String[] args) throws FileNotFoundException { 
     File test = new File("test.txt"); 
     Scanner read = new Scanner (test); 
     String input; 
     input = read.next(); 
     System.out.println (input); 
    } 
} 

當我運行這段代碼,我得到這個錯誤文件未找到錯誤,當文件在項目文件夾

Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified) 

at java.io.FileInputStream.open(Native Method) 

at java.io.FileInputStream.<init>(Unknown Source) 

at java.util.Scanner.<init>(Unknown Source) 
    at Test.main(Test.java:9) 

我已經創建的文本文件,它是正確的項目文件夾,但它沒有找到它。

編輯

InputStream file = getClass().getResourceAsStream("highScore.txt"); 
BufferedReader br = new BufferedReader (new InputStreamReader(file,"UTF-8")); 
String text; 
text = br.readLine(); 
while (text!=null) { 
    System.out.println (text); 
} 

我試過,但我得到一個NullPointerException錯誤

這是一個小程序。

+0

你在哪裏添加「的test.txt」文件? –

+1

相關:http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream – BalusC

回答

0

當您啓動程序時,您必須與test.txt位於同一個目錄中。例如:

cd dir/with/textfile 
ls 
    test.txt 
java -cp my.jar com.toby.guo.Test 

或者,你可以給出完整的文件路徑:

File test = new File("/home/dir/with/textfile/test.txt"); 
0

當你閱讀使用new File("test.txt");一個文件的文件應該是直接的電流工作目錄內的java程序。

或者你也可以把文件與您一起Test.java並閱讀喜歡:

Test.class.getResourceAsStream("test.txt"); 
+0

這個目錄在哪裏?我試過這樣閱讀它,它的工作原理,但我不知道如何將輸入流更改爲字符串。 –

+0

在這個視頻中:http://www.youtube.com/watch?v = x9c8PNLR8AU,這個人把文件放在項目文件夾中,它工作。 –

相關問題