spring启动ResourceLoader遍历jar包中的文件
spring boot ResourceLoader traverse the files in the jar package
我使用spring的ResourceLoader来遍历jar中的文件。但我想知道文件的类型(目录或文件)。
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");
}
我知道:
resource.getInputStream()
可以获取文件的内容。但我想知道文件的类型。
Spring 的 ResourceLoader
用于为类路径、文件系统、Web 等上的资源创建资源处理程序。
它的目的不是遍历 jar 文件的内容和探测文件与目录。
我不确定您的最终目标是什么,但是对于来自 ResourceLoader
的单个加载资源,您可以执行以下操作:
String filename = resource.getFilename();
String type = URLConnection.guessContentTypeFromName(resource.getFilename());
这将为您提供根据扩展名猜测的文件类型。
遍历 Jar 条目
为了遍历所有 jar 条目,您必须在运行时加载 jar 文件并执行如下操作:
//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();
另一种方法是将 jar 文件作为 Zip 文件打开并使用 ZipEntry to probe for file vs directory, or to create a new filesystem for the Jar's content (FileSystems.newFileSystem) 然后您可以直接使用 Path
和 File
。
我使用spring的ResourceLoader来遍历jar中的文件。但我想知道文件的类型(目录或文件)。
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");
}
我知道:
resource.getInputStream()
可以获取文件的内容。但我想知道文件的类型。
Spring 的 ResourceLoader
用于为类路径、文件系统、Web 等上的资源创建资源处理程序。
它的目的不是遍历 jar 文件的内容和探测文件与目录。
我不确定您的最终目标是什么,但是对于来自 ResourceLoader
的单个加载资源,您可以执行以下操作:
String filename = resource.getFilename();
String type = URLConnection.guessContentTypeFromName(resource.getFilename());
这将为您提供根据扩展名猜测的文件类型。
遍历 Jar 条目
为了遍历所有 jar 条目,您必须在运行时加载 jar 文件并执行如下操作:
//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();
另一种方法是将 jar 文件作为 Zip 文件打开并使用 ZipEntry to probe for file vs directory, or to create a new filesystem for the Jar's content (FileSystems.newFileSystem) 然后您可以直接使用 Path
和 File
。