簡體   English   中英

如何從java資源文件夾內的文件夾中獲取所有文件的列表

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

我在“協議”文件夾中多個文件 我想獲取位於 java 資源文件夾(src/main/resources/protocol/...)內的“protocol”文件夾中的文件列表。

因此,當我嘗試訪問任何一個文件時,它在 Eclipse IDE(使用 main 方法)和 wildfly 部署中都可以正常工作。 它在文件中給出了行。

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

但是當嘗試讀取文件夾時,它在 Eclipse IDE(獲取文件名列表)中工作正常,但在 Wildfly 部署中不起作用,它給出了一個空白列表 []。

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

我正在使用 jboss wildfly 服務器版本:9.0.1 和 java 版本“1.8.0_161”。

謝謝你的幫助。

找到了獲取文件夾內所有文件的解決方案。

如果我們嘗試通過 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;
    }

就像是:

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());

它表明 Path 是 File 的更精細概括。 它使用jar:file:協議(如http :)協議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM