pankti
pankti

Reputation: 195

Read properties file outside JAR file - java 8 not recognizing file

Replicated the same scenario as in below sample program.

I am trying to read a file Test.txt that is located outside my classes folder. I'm using getResourceAsStream method to locate the file, but it's not recognizing. As long as my file is inside the classes folder it recognizes.

InputStream propFileInpStream = LocateFile.class.getResourceAsStream("../../../"+PROP_FILE);

Not recognizing if outside classes folder

enter image description here

Recognizing if anywhere inside classes folder structure

enter image description here

Upvotes: 1

Views: 2457

Answers (4)

pankti
pankti

Reputation: 195

Thanks all for the help, I just replaced the line

InputStream propFileInpStream = LocateFile.class.getResourceAsStream("..\\\\"+PROP_FILE);

With the below changes:

InputStream propFileInpStream = new FileInputStream("..\\\\"+PROP_FILE);

Upvotes: 0

You need to do it differently for things outside the classpath. You may want to ask the JVM where the bytecode for your class was stored physically, and then navigate from there to the file you need. Note that this works differently when the class file is stored in a jar.

From http://www.exampledepot.com/egs/java.lang/ClassOrigin.html: (old link)

// Get the location of this class
Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/

Upvotes: 0

Tunaki
Tunaki

Reputation: 137094

This is normal and completely expected.

Class.getResourceAsStream(name) attempts to find a resource with the given name, not an arbitrary file. A resource is a file that is present in the classpath of your application. If that file is not in the classpath, you can't use that method to retrieve an InputStream from it.

What you can do is use the Java NIO.2 API with the help of Files.newInputStream(path):

Opens a file, returning an input stream to read from the file.

This method will open a file (and not a resource) for reading. You can get a Path instance with the static factory Paths.get(first, more...). You can give an absolute path to the file or a path that is relative to the location of the jar file.

Sample code:

try (InputStream propFileInpStream = Files.newInputStream(Paths.get(path))) {
    // do something with the input stream
}

Upvotes: 2

Wand Maker
Wand Maker

Reputation: 18762

LocateFile.class.getResourceAsStream will look for the file in class path.

If you need to access file outside class path, then, either you add the location of that file to class path or use absolute path and use suggestions from this thread to read it as a stream.

Upvotes: 0

Related Questions