[英]Get folder from Resources folder JAVA
Hi everyone I can't figure out with this problem : this line of code should work大家好,我无法解决这个问题:这行代码应该可以工作
File[] file = (new File(getClass().getResource("resources/images_resultats"))).listFiles();
I want a list of File, these Files are under "images_resultats" under "resources".我想要一个文件列表,这些文件在“资源”下的“images_resultats”下。
It won't work if resources/images_resultats
is not in your classpath and/or if it is in a jar file.如果
resources/images_resultats
不在您的类路径中和/或如果它在 jar 文件中,它将不起作用。
Your code is not even correct it should something like:您的代码甚至不正确,它应该类似于:
File[] file = (new File(getClass().getResource("/my/path").toURI())).listFiles();
You can determine what files are in a folder in resources (even if its in a jar) using the FileSystem class.您可以使用 FileSystem 类确定资源文件夹中的文件(即使它在 jar 中)。
public static void doSomethingWithResourcesFolder(String inResourcesPath) throws URISyntaxException {
URI uri = ResourcesFolderUts.class.getResource(inResourcesPath).toURI();
try( FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap() ) ){
Path folderRootPath = fileSystem.getPath(inResourcesPath);
Stream<Path> walk = Files.walk(folderRootPath, 1);
walk.forEach(childFileOrFolder -> {
//do something with the childFileOrFolder
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
inResourcesPath should be something like "/images_resultats"
inResourcesPath 应该类似于
"/images_resultats"
Note that the childFileOrFolder paths can only be used while the FileSystem remains open, if you try to (for example) return the paths then use them later you've get a file system closed exception.请注意, childFileOrFolder 路径只能在 FileSystem 保持打开状态时使用,如果您尝试(例如)返回路径然后稍后使用它们,则会出现文件系统关闭异常。
Change ResourcesFolderUts for one of your own classes为您自己的类之一更改 ResourcesFolderUts
Assuming that resources folder is in classpath, this might work.假设资源文件夹在类路径中,这可能会起作用。
String folder = getClass().getResource("images_resultats").getFile();
File[] test = new File(folder).listFiles();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.