How to get folder paths inside a jar file?

Okay, so in the IDE it runs great and says the file exists, but once I pack it into a jar this code:


File levelFolder = new File(getClass().getResource("data/level").getPath()); 
System.out.println("exists = " + levelFolder.exists());

says the folder doesn’t exist. any idea why?

For resources in a JAR, you must use ‘URL’ instead of ‘File’.

This snippet works with the IDE (Eclipse) and with a JAR :

URL urlClasses = getClass().getResource("");
String urlText = urlClasses.toString();   

String pathImages = null;
if (urlText.startsWith("jar"))
{  
  pathImages= urlText.replaceAll("abc", "images"); 
}
else if (urlText.startsWith("file"))
{
  int i = urlText.indexOf("classes");
  pathImages = urlText.substring(0, i) + "images/";
}
        
final String IMAGE = "myImage.png";

URL urlImages = null;
try { urlImages = new URL(pathImages + IMAGE); }
catch (MalformedURLException e) { e.printStackTrace(); }

// 'abc' is the name of the root-package, 
// 'images' is the name of the resource-directory and is 
// placed in the same directory as 'src' and 'classes'.

I was trying to see how many files were in a sub-directory of my jar, so images don’t mean anything to me, I need a File.

A java.io.File is a representation of a file on a physical device. Hence you can’t use a java.io.File to refer to a ‘file’ within an archive.

Use a ZipInputStream of a JarInputStream and iterate over the Entries. Sometimes directories do not have an entry, but it’s easy to look at all the ‘file’ entries and reconstruct the directories from there.

I was just wondering about use case for that situation you have CyanPrime … how come you don’t know structure of a jar at runtime, do you change it in the game or do you add new resources dynamically this way?