artouiros
artouiros

Reputation: 3987

Read a file from inside the .jar folder

I need to read the file, that is inside the jar folder in this way:

 DataSource coverdata = new FileDataSource(new File("here is the path"));

How do I get the exact path? I am using a library, so the only way I can acces file is new File(), no inputstreams.

Upvotes: 1

Views: 1355

Answers (3)

Vicente Plata
Vicente Plata

Reputation: 3380

What about creating a new temporal file, with the InputStream (getResourceAsStream() ) methods that @home already talked about, and then reading it as a normal file?

Upvotes: 0

AlexR
AlexR

Reputation: 115328

You are on the wrong way. File is only something that is directly written on file system. File inside jar is not a file from java API point of view.

To read this file you have to parse JAR using either JarInputStream or ZipInputStream, get to the interesting entry and read from the input stream. It is not hard to do but you have to write several lines of code.

Other approach is using VFS package from jakarta.org. It provides you unified view on elements of different files systems, ZIP, TAR and other container formats.

Upvotes: 1

home
home

Reputation: 12538

Call ClassLoader.getResourceAsStream()::InputStream or ClassLoader.getResource()::URL.

See:

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)

The JAR file containing the requested file must be in the classpath.

Upvotes: 3

Related Questions