Question

Hi I wanted to run a java Eclipse project form command line.. I tried making a Jar and Runnable Jar (Both options), with the manifest when needed.

The problem which I cannot solve is that it always ends up giving me a FileNotFound error when My program tried to read a txt file. How do I solve this error? I cannot find it online.

Thanks

Example:

in = new BufferedReader(new FileReader("CompanyNameListModified.txt"));

Error:

Exception in thread "main" java.io.FileNotFoundException: CompanyNameListModified.txt (No such file or directory)

Was it helpful?

Solution

Assuming that the text file is in the jar itself, then don't grab it as a File, since technically, these don't exist in jar files, but rather get it as a resource.

e.g.,

package foo;

import java.io.InputStream;
import java.util.Scanner;

public class TestResource {
   public static void main(String[] args) {
      ClassLoader classLoader = ClassLoader.getSystemClassLoader();     
      String resourceName = "foo/movies.txt"; // path relative to classloader
      InputStream inStream = classLoader.getResourceAsStream(resourceName);
      Scanner scanner = new Scanner(inStream);
      while (scanner.hasNextLine()) {
         System.out.println(scanner.nextLine());
      }
      if (scanner != null) {
         scanner.close();
      }
   }   
}

the contents of the jar file are:

C:\Users\hovercraft\Jar files>jar tf TestResource.jar
META-INF/MANIFEST.MF
foo/TestResource.class
foo/TestResource.java
foo/movies.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top