-1

With this code I want a .jar-file to read the text-file "file.txt" which is located in the jar in folder data. This is a application is programmed with Processing, so all files I want to read are in the data folder. Can anybody explain why I get a NullPointerException? The file exists and contains text.

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");
  }
}    
  • Culprit is `InputStream is = getClass().getResourceAsStream("/data/file.txt");` is is null. – SMA Feb 08 '15 at 13:05
  • possible duplicate of http://stackoverflow.com/questions/16842306/how-to-read-a-file-from-jar-archive or http://stackoverflow.com/questions/3369794/how-to-a-read-file-from-jar-in-java – emin Feb 08 '15 at 13:23

1 Answers1

0

getClass().getResourceAsStream("/data/file.txt"); returns null, because it uses that class' system loader which can't see your jar. Use instead

YourClassName.class.getResourceAsStream("/data/file.txt");
Zereges
  • 5,139
  • 1
  • 25
  • 49