2

I am trying to read a file from my executable .jar file but it keeps getting null values.

I have this code:

public DanceEventTicketScanner(String txtfile){
    sv = new ScannerView(this);
    findcode = false;
    InputStream is = this.getClass().getResourceAsStream("/resources/copy.csv");
    if (is == null) JOptionPane.showMessageDialog(null, "Resource not located.");
}

In the JAR file i have (as normal) a folder containing all my .class files and in the same directory a folder named resources which holds the copy.csv file.

This code however does not recognize the file.

Does anyone have any ideas?

user1604443
  • 59
  • 4
  • 8
  • Related question: http://stackoverflow.com/questions/3369794/how-can-i-read-file-from-jar-in-java –  Mar 05 '13 at 18:36
  • In the same directory as what? /resources would need to be in the root of the JAR file for your code to work. – user207421 Mar 06 '13 at 00:17

2 Answers2

4

Remove the first slash:

InputStream is = this.getClass().getResourceAsStream("resources/copy.csv");
Laurel
  • 5,965
  • 14
  • 31
  • 57
A4L
  • 17,353
  • 6
  • 49
  • 70
2

getClass().getResourceAsStream(..) will use a path relative to the class (so inc. package dirs). getClass().getClassLoader().getResourceAsStream(..) will use an absolute path. So change your code and get the class loader and it will work.

Zubzub
  • 782
  • 7
  • 18