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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 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); } |