[英]In Java is it possible to get a directory file listing inside a WAR classpath using a resource path?
我在类路径的目录中有一个文件列表,我需要阅读,并且更喜欢使用File API,但看起来我不能在存档中这样做。 这适用于我的本地环境单元测试,但是当我在EAR中部署为WAR时,文件列表将返回null:
File dir = new File(getClass().getClassLoader().getResource("mydir").getPath());
File[] files = dir.listFiles();
如果未解压变war,则无法使用File API,但可以使用Servlet API。
ServletContext的getResourcePaths方法可用于检索“directory”的所有成员,然后使用getResource或getResourceAsStream来检索目录中文件的内容。
for (String s : context.getResourcePaths("foo")) {
InputStream contents = context.getResourceAsStream(s);
//do something with the contents
}
如果您使用的是Java SE 7,请尝试:
Path jarPath = Paths.get(...);
try (FileSystem jarFS = FileSystems.newFileSystem(jarPath, null)) {
Path dirJarPath = jarFS.getPath("/foo/mydir");
<use a FileVisitor and Files.walkFileTree>
}
http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitor.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.