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