How to Read a File from a Jar File

Reading a resource file from within jar

Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:

try (InputStream in = getClass().getResourceAsStream("/file.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
// Use resource
}

As long as the file.txt resource is available on the classpath then this approach will work the same way regardless of whether the file.txt resource is in a classes/ directory or inside a jar.

The URI is not hierarchical occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt. You cannot read the entries within a jar (a zip file) like it was a plain old File.

This is explained well by the answers to:

  • How do I read a resource file from a Java jar file?
  • Java Jar file: use resource errors: URI is not hierarchical

How to read a file from a jar file?

You can't use File, since this file does not exist independently on the file system. Instead you need getResourceAsStream(), like so:

...
InputStream in = getClass().getResourceAsStream("/1.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
...

Reading a Text File from a .jar

Try using this

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(yourFileName).getFile());

if doesn't work put the resources folder inside src folder

How to read a class file from an extracted jar file?

Use a decompiler. I prefer using Fernflower, or if you use IntelliJ IDEA, simply open .class files from there, because it has Fernflower pre-installed.

Or, go to javadecompilers.com, upload your .jar file, use CFR and download the decompiled .zip file.

However, in some cases, decompiling code is quite illegal, so, prefer to learn instead of decompiling.

How to read a file in another jar file?

It is the case that the general class loader will take the path the comes first on the class path, and evidently A.jar comes first, before B.jar.

String someUniqueResourceInBJar = "...";
URL url = B.class.getResource(someUniqueResourceInBJar);
url = new URL(url.getPath().replaceFirst(someUniqueResourceInBJar + "$", "")
+ "META-INF/MANIFEST.MF";
url.openStream();

The url will be something like "jar:file://.../B.jar!META-INF/MANIFEST.MF".


Alternatively getting the class URL:

URL url = b.class.getProtectionDomain().getCodeSource().getLocation();


Related Topics



Leave a reply



Submit