I have some code that works correct when run from Eclipse, but throws FileNotFoundException when run from jar.

Even more this code properly worked before but stopped after… I don’t know. May be after some Windows update?

Here is the code

 

   1: String path = Thread.currentThread().getContextClassLoader().getResource("stopwords.txt").getPath();

   2: System.out.println(path);

   3: BufferedReader input = new BufferedReader(new FileReader(new File(filePath)));

Output: file:/F:/PROMOTION/executor.jar!/stopwords.txt  — correct path to file, so file is found by getResource(…) method.

Exception thrown from code line 3:

java.io.FileNotFoundException: file:\F:\PROMOTION\executor.jar!\stopwords.txt (The filename, directory name, or volume label syntax is incorrect)

What cause for this strange behavior  I don’t know. Stackoverflow has about 4 questions about same issue, but not explain cause as well.

But workaround (at least in my case) the next: to use getResourceAsStream() instead of getResource().getPath() and Scanner instead of BufferedReader.

Full working code is looks like:

   1: InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("stopwords.txt");

   2: List<String> lines = new ArrayList<String>();

   3:          Scanner scanner = new Scanner(stream);

   4:             try {

   5:               while (scanner.hasNextLine()){

   6:                 lines.add(scanner.nextLine());

   7:               }

   8:             }

   9:             finally{

  10:               scanner.close();

  11:             }

Filed under: java

Like this post? Subscribe to my RSS feed and get loads more!