How to check if a URL is a directory

Hey guys, I’m trying to build a framework that will allow a user to navigate the contents of a signed jar file, and need it to support looking into various subdirectories. How would one go about figuring out whether or not a given resource is a directory?

I’m getting the initial directory using MapSelection.getClass().getResource("/CremelianWars/Maps/") which returns a URL. The File class has a method for checking if it’s a directory or not, but a URL doesn’t seem to have one.

Thanks

look at the protocol URL.getProtocol() if it is “file” than use (new File(f)).isDirectory()

something like :

if (url.getProtocol().equals("file")) 
 return ( new File(url.getFile() ) ).isDirectory();
return false;

A URL is the location of a resource, not necessarily a file system. The resource may not have the concept of a directory.

If the URL points to a file, you can just check if the file is a directory. If it points to a JAR, you have to open the JAR, get the corresponding entry, and see if it is a directory. Unfortunately, Java’s zip API is quite crappy. I messed around and got the below. While it seems to work, I arrived at it by trial and error because the ZipEntry#isDirectory only seems to return true when the path ends in slash, and ZipFile#getInputStream returns null, and the javadocs don’t even tell what the hell that means.

static public boolean isDirectory (URL url) throws IOException {
	String protocol = url.getProtocol();
	if (protocol.equals("file")) {
		return new File(url.getFile()).isDirectory();
	}
	if (protocol.equals("jar")) {
		String file = url.getFile();
		int bangIndex = file.indexOf('!');
		String jarPath = file.substring(bangIndex + 2);
		file = new URL(file.substring(0, bangIndex)).getFile();
		ZipFile zip = new ZipFile(file);
		ZipEntry entry = zip.getEntry(jarPath);
		boolean isDirectory = entry.isDirectory();
		if (!isDirectory) {
			InputStream input = zip.getInputStream(entry);
			isDirectory = input == null;
			if (input != null) input.close();
		}
		return isDirectory;
	}
	throw new RuntimeException("Invalid protocol: " + protocol);
}

That seems to work, thanks!

Unfortunately, I have just realized that the way I actually read the contents of the folder no longer works when the resources are packaged into a jar. Before, I would open up a URLConnection on a URL, then read all of the filenames in the folder using a BufferedReader. However, inside a jar, the following method is not able to obtain the folder as a URL.


URL directory = this.getClass().getResource(mapFolder);