Reputation: 269
I use spring's ResourceLoader to traverse the files in the jar . but i want to know the file's type(directory or file)。
Resource resource = defaultResourceLoader.getResource(templatePathPrefix + File.separator + templateSourcePath);
File templateSourceFile = null;
try {
//throws java.io.FileNotFoundException:
templateSourceFile = resource.getFile();
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Cannot find file " + resource, e);
}
if (templateSourceFile.isDirectory()) {
System.out.println("it is directory");
} else {
System.out.println("it is just file");
}
I know:
resource.getInputStream()
can get the file's content. but i want to know the file's type.
Upvotes: 0
Views: 1284
Reputation: 31433
Spring's ResourceLoader
is made for creating a resource handler for a resource on the classpath, filesystem, web etc.
It's purpose is not to traverse contents of jar files and probe for file vs directory.
I am not sure what you end goal here is, but for a single loaded resource from ResourceLoader
you can do something like:
String filename = resource.getFilename();
String type = URLConnection.guessContentTypeFromName(resource.getFilename());
which will give you the file type, guessed from the extension.
Traversing Jar Entries
In order to traverse all jar entries, you have to load the jar file at runtime and do something like:
//String or File handler to JAR file
JarFile jar = new JarFile(file);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
System.out.println(jarEntry.getName() + ": " + jarEntry.isDirectory());
}
jar.close();
Another approach would be to open the jar file as a Zip and use ZipEntry to probe for file vs directory, or to create a new filesystem for the Jar's content (FileSystems.newFileSystem) and then you can work with Path
and File
directly.
Upvotes: 2