kavita
kavita

Reputation: 845

finding static file in jar

I am trying to use a jar file which itself is a web application in another web project. In my jar which i have created using eclipse's export to jar functionality, I have stored a csv file in a folder. To use relative paths in the code in the jar I access it using

MyClass.class.getResource(ApplicationConstants.ALIASESFILE).getPath(); 

and this works fine when I deploy (glassfish) and use the project as a separate application. But when I am using the same from within another project, it gives a path as shown below

D:\javaProjects\AutomodeGS_Prachi\lib\internal\RESTWSGS.jar!\aliases\aliases.csv

I am getting a file notfound exception.What could be wrong?

Upvotes: 0

Views: 1174

Answers (2)

Stephen C
Stephen C

Reputation: 719376

The getResource() method is returning a "jar:" URL. The path component of that URL is not a normal filesystem pathname, and can't be opened directly using Java's file classes.

The simple way to do this is to use Class.getResourceAsStream(...) to open the stream. If you need an "identifier" for the JAR entry, use Class.getResource(...), but then open the stream using URL.openStream().

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240948

This works fine from glassfish may be because glassfish has exploded jar on file system so that your csv file is acutually a file to the file system,

if you try to read it from another project it fails because the jar containing your file is in classpath that is fine, but the csv file is under jar file and it is no longer a File

You can read it as Stream

InputStream is = MyClass.class.getResourceAsStream(ApplicationConstants.ALIASESFILE); 

Upvotes: 2

Related Questions