使用这段代码,我想要一个.jar文件来读取位于jar文件夹数据中的文本文件“file.txt”。这是一个使用Processing编程的应用程序,因此我想要读取的所有文件都在数据文件夹中。任何人都可以解释为什么我得到NullPointerException?该文件存在并包含文本。
import java.io.*;
void setup() {
size(500, 500);
try {
// HERE I TRY TO READ THE FILE WHICH IS LOCATED IN THE JAR FILE IN THE FOLDER "DATA"
InputStream is = getClass().getResourceAsStream("/data/file.txt");
// HERE I GET A NULL-POINTER-EXCEPTION BECAUSE THE FILE CANNOT BE READ (IS = NULL, WHY IS THE INPUT STREAM NULL?)
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// THE FIRST LINE OF THE DOCUMENT IS READ AND PRINTED IN THE CONSOLE
String read = br.readLine();
br.close();
println(read);
}
catch (IOException e) {
// IF THE FILE DOESN'T EXIST AN IO-EXCEPTION WILL BE CAUGHT
println("Error reading file");
}
}
答案 0 :(得分:0)
getClass().getResourceAsStream("/data/file.txt");
返回null,因为它使用了该类'系统装载机,看不到你的罐子。改为使用
YourClassName.class.getResourceAsStream("/data/file.txt");