How to Access a Folder Inside of a Resource Folder from Inside My Jar File

How can I access a folder inside of a resource folder from inside my jar File?

Finally, I found the solution:

final String path = "sample/folder";
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

if(jarFile.isFile()) { // Run with JAR file
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
while(entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
if (name.startsWith(path + "/")) { //filter according to the path
System.out.println(name);
}
}
jar.close();
} else { // Run with IDE
final URL url = Launcher.class.getResource("/" + path);
if (url != null) {
try {
final File apps = new File(url.toURI());
for (File app : apps.listFiles()) {
System.out.println(app);
}
} catch (URISyntaxException ex) {
// never happens
}
}
}

The second block just work when you run the application on IDE (not with jar file), You can remove it if you don't like that.

Access resource folder within jar

Not understanding the difference between absolute and relative paths when loading resources in Java via getResourceAsStream() is a common source of errors leading to NullPointerException.

Assuming the following structure and content:

My Project
|-src
|-main
|-java
| |-SomePackage
| |-SomeClass.java
|-resources
|-Root.txt
|-SomePackage
|-MyData.txt
|-SomePackage2
|-MySubData.txt

Content will be re-organized as following in the .jar:

|-Root.txt
|-SomePackage
|-SomeClass.java
|-MyData.txt
|-SomePackage2
|-MySubData.txt

The following indicates what works and what does not work to retrieve resource data:

InputStream IS;
IS = SomeClass.class.getResourceAsStream("Root.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("/Root.txt"); // OK

IS = SomeClass.class.getResourceAsStream("/MyData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("MyData.txt"); // OK

IS = SomeClass.class.getResourceAsStream("/SomePackage/MyData.txt"); // OK

IS = SomeClass.class.getResourceAsStream("SomePackage/MyData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("MySubData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("SomePackage/SomePackage2/MySubData.txt"); // OK

IS = SomeClass.class.getResourceAsStream("/SomePackage/SomePackage2/MySubData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("/SomePackage2/MySubData.txt"); // Not OK

IS = SomeClass.class.getResourceAsStream("SomePackage2/MySubData.txt"); // OK

getResourceAsStream() operates relative to the package corresponding to the called Class instance.

How to include the resources folder in a jar file

Follow these steps:

  1. click project -> properties -> Build Path -> Source -> Add Folder and select resources folder.

  2. create your JAR!

EDIT: you can make sure your JAR contains folder by inspecting it using 7zip.

Reefer this link as well How do I add a resources folder to my Java project in Eclipse

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

Open file that is in the resource folder/inside jar

What you need is to read the file as a resource, not as a file with

InputStream stream = getClass().getClassLoader().getResourceAsStream("file.txt");

Relevant question and answers can be found here:

How to really read text file from classpath in Java

How to load a folder from a .jar?

There's no way this will work. You're trying to create a File object from a resource inside a JAR. That isn't going to happen. The best method to load resources is to make one your package folders a resource folder, then make a Resources.jar in it or something, dump your resources in the same dir, and then use Resources.class.getResourceAsStream(resFileName) in your other Java class files.

If you need to 'brute force' the subfiles in the JAR directory pointed to by the URL given by getResource(..), use the following (although it's a bit of a hack!). It will work for a normal filesystem too:

  /**
* List directory contents for a resource folder. Not recursive.
* This is basically a brute-force implementation.
* Works for regular files and also JARs.
*
* @author Greg Briggs
* @param clazz Any java class that lives in the same place as the resources you want.
* @param path Should end with "/", but not start with one.
* @return Just the name of each member item, not the full paths.
* @throws URISyntaxException
* @throws IOException
*/
String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
URL dirURL = clazz.getClassLoader().getResource(path);
if (dirURL != null && dirURL.getProtocol().equals("file")) {
/* A file path: easy enough */
return new File(dirURL.toURI()).list();
}

if (dirURL == null) {
/*
* In case of a jar file, we can't actually find a directory.
* Have to assume the same jar as clazz.
*/
String me = clazz.getName().replace(".", "/")+".class";
dirURL = clazz.getClassLoader().getResource(me);
}

if (dirURL.getProtocol().equals("jar")) {
/* A JAR path */
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
while(entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.startsWith(path)) { //filter according to the path
String entry = name.substring(path.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0) {
// if it is a subdirectory, we just return the directory name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
return result.toArray(new String[result.size()]);
}

throw new UnsupportedOperationException("Cannot list files for URL "+dirURL);
}

You can then modify the URL given by getResource(..) and append the file on the end, and pass these URLs into getResourceAsStream(..), ready for loading. If you didn't understand this, you need to read up on classloading.

How do I access the content of folders inside a jar file?

You could get path to the jar file and open it with ZipInputStream list all the files inside that jar.

To know the path of the running jar, try using:

InputStream in = MyClass
.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.openStream();

See also: How do I list the files inside a JAR file?

update

I've compiled an ran your solution and works perfect:

C:\java\injar>dir
El volumen de la unidad C no tiene etiqueta.
El número de serie del volumen es: 22A8-203B

Directorio de C:\java\injar

21/02/2011 06:23 p.m. <DIR> .
21/02/2011 06:23 p.m. <DIR> ..
21/02/2011 06:23 p.m. 1,752 i18n.jar
21/02/2011 06:23 p.m. <DIR> src
21/02/2011 06:21 p.m. <DIR> x

C:\java\injar>jar -tf i18n.jar
META-INF/
META-INF/MANIFEST.MF
I18n.class
x/
x/y/
x/y/z/
x/y/z/hola.txt

C:\java\injar>type src\I18n.java
import java.util.*;
import java.net.*;
import java.util.jar.*;
class I18n {
public static void main( String ... args ) {
getLocaleListFromJar();
}
private static List<Locale> getLocaleListFromJar() {
List<Locale> locales = new ArrayList<Locale>();
try {
URL packageUrl = I18n.class.getProtectionDomain().getCodeSource().getLocation();
JarInputStream jar = new JarInputStream(packageUrl.openStream());
while (true) {
JarEntry entry = jar.getNextJarEntry();
if (entry == null) {
System.out.println( "entry was null ");
break;
}
String name = entry.getName();
System.out.println( "found : " +name );
/*if (resourceBundlePattern.matcher(name).matches()) {
addLocaleFromResourceBundle(name, locales);
}*/
}
} catch (Exception e) {
System.err.println(e);
return null;
//return getLocaleListFromFile(); // File based implementation in case resources are not in jar
}
return locales;
}
}

C:\java\injar>java -jar i18n.jar
found : I18n.class
found : x/
found : x/y/
found : x/y/z/
found : x/y/z/hola.txt
entry was null


Related Topics



Leave a reply



Submit