6

I have a project structure that looks like this:

Tester  
\-- src  
    |-- hello.java  
    \-- vocabulary.csv

I load the csv file using getResource:

url = this.getClass().getResource("vocabulary.csv");
System.out.println(url.getPath());
new FileReader(url.getPath());

The program works completly fine until I export the project to a runnable jar file. Even though the URL is still valid (he prints the path instead of null) the console shows this:

jar:file:/home/malte/Desktop/vocs.jar!/main/vocabulary.csv
Exception in thread "main" java.io.FileNotFoundException: file:/home/malte/Desktop/vocs.jar!/main/vocabulary.csv (No such file or directory)

Can you explain me why this happens and how I can solv the issue?

P.S. I am using Xtend instead of pure Java

Dmitry Minkovsky
  • 36,185
  • 26
  • 116
  • 160
schrobe
  • 767
  • 2
  • 8
  • 29

1 Answers1

15

You need to use

InputStream is = this.getClass().getResourceAsStream();

once you package your source as a jar. You have just one file : your jar. Your vocabulary.csv is no longer a standalone file on filesystem anymore.

You can read more here.

rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • Thanks! And instead of **new FileReader(url.getPath())** I now use **new InputStreamReader(is)** – schrobe Aug 09 '13 at 16:25
  • This solution doesn't work. Also tried with URL. I have used Eclipse IDE Export option and chose "Package jars" when exported all the necessary dependencies – ha9u63a7 Jul 13 '17 at 19:46