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錯誤
這是一個小程序。
你在哪裏添加「的test.txt」文件? –
相關:http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream – BalusC