简体   繁体   English

如何从java资源文件夹内的文件夹中获取所有文件的列表

[英]how to get list of all files from folder inside java resources folder

I am having multiple files inside 'protocol' folder .我在“协议”文件夹中多个文件 I want to get list of files inside 'protocol' folder which is inside java resources folder (src/main/resources/protocol/...).我想获取位于 java 资源文件夹(src/main/resources/protocol/...)内的“protocol”文件夹中的文件列表。

so when i tried to access any one file it works fine in eclipse IDE(using main method) and also in wildfly deployment.因此,当我尝试访问任何一个文件时,它在 Eclipse IDE(使用 main 方法)和 wildfly 部署中都可以正常工作。 it gives lines inside files.它在文件中给出了行。

List<String> files = IOUtils.readLines(classLoader.getResourceAsStream("protocol/protocol1.csv"));

but when try to read folder it works fine in eclipse IDE(got list of file names) but does not work in wildfly deployment it gives a blank list [].但是当尝试读取文件夹时,它在 Eclipse IDE(获取文件名列表)中工作正常,但在 Wildfly 部署中不起作用,它给出了一个空白列表 []。

List<String> files = IOUtils.readLines(classLoader.getResourceAsStream("protocol"));

i am using jboss wildfly server version:9.0.1 and java version "1.8.0_161".我正在使用 jboss wildfly 服务器版本:9.0.1 和 java 版本“1.8.0_161”。

Thanks for any help.谢谢你的帮助。

Found solution to fetch all files inside folder.找到了获取文件夹内所有文件的解决方案。

if we try to access folder by getResource() method it will return in terms of vfs protocol and we need to convert that to如果我们尝试通过 getResource() 方法访问文件夹,它将根据 vfs 协议返回,我们需要将其转换为

public List<String> loadFiles() throws IOException, Exception {
        List<String> fileNames = new ArrayList<>();
        URL resourceUrl = getClass().getResource("/protocol");
        VirtualJarInputStream jarInputStream = (VirtualJarInputStream) resourceUrl.openStream();
        JarEntry jarEntry = null;
        while ((next = jarInputStream.getNextJarEntry()) != null) {
            fileNames.add(jarEntry.getName());
        }
        return fileNames;
    }

Something like:就像是:

URL url = classLoader.getResourceAsStream("protocol");
Path dirPath = Paths.get(url.toURI());
Stream<Path> paths = Files.list(dirPath);
List<String> names = paths
        .map(p -> p.getFileName().toString())
        .collect(Collectors.toList());

It shows that Path is a more refined generalisation of File.它表明 Path 是 File 的更精细概括。 It uses the jar:file: protocol ( protocols like http:).它使用jar:file:协议(如http :)协议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM