Перечислите имена всех подкаталогов в папке ресурсов JAR - PullRequest
0 голосов
/ 26 февраля 2019

Я упаковал свой проект Spring Boot в JAR, используя maven.Я хочу прочитать имена всех каталогов в разделе «static / foo» в папке ресурсов.

Попробовал следующее с помощью библиотеки Apache Commons:

String fooPath = "static/foo/";
List<String> fooFolders = IOUtils.readLines(this.getClass().getClassLoader().getResourceAsStream(fooPath), Charsets.UTF_8);
// The fooFolders list is empty ...

ОБНОВЛЕНИЕ

Это решение работало (немного изменено с https://stackoverflow.com/a/48190582/1427624) с использованием JarFile :

String fooPath = "static/foo";
URL url = Thread.currentThread().getContextClassLoader().getResource(fooPath);

// Not running from JAR
if (url.getProtocol().equals("file"))
{
    try {
        // Get list of subdirectories' folder names
        List<String> fooFolders = IOUtils.readLines(this.getClass().getClassLoader().getResourceAsStream(fooPath), Charsets.UTF_8);

        // Loop subdirectories
        for (String fooFolder : fooFolders) {
            // The current subdirectory path
            String fooFolderPath = fooPath + "/" + fooFolder;

            // Loop all files in this subdirectory, if needed
            List<String> fooFiles = IOUtils.readLines(this.getClass().getClassLoader().getResourceAsStream(fooFolderPath), Charsets.UTF_8);

            for (String fooFile : fooFiles) {
                // The updated path of the file
                String fooFilePath = fooFolderPath + "/" + fooFile;

                // Read the file's content
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fooFilePath);
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, Charsets.UTF_8);
                String fileContent = writer.toString();
            }
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

// Running from JAR
else if (url.getProtocol().equals("jar")) {
    String dirname = fooPath + "/";
    String path = url.getPath();
    String jarPath = path.substring(5, path.indexOf("!"));

    List<String> fooFolders = new ArrayList<String>();
    HashMap<String, List<String>> fooFiles = new HashMap<String, List<String>>();

    try (JarFile jar = new JarFile(URLDecoder.decode(jarPath, StandardCharsets.UTF_8.name()))) {
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String jarEntryName = entry.getName();

            String updated_dir_name = "BOOT-INF/classes/" + dirname;

            // Only get files that are in the directory we require (fooPath)
            if (jarEntryName.startsWith(updated_dir_name) && !dirname.equals(updated_dir_name)) {

                // Get the resource URL
                URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(jarEntryName);

                // Files only
                if (!jarEntryName.endsWith("/")) {

                    // Split the foo number and the file name
                    String[] split = jarEntryName.split("/");

                    // First level subdirectories inside fooPath
                    // BOOT-INF/classes/static/foo/1/myfile.html
                    // We want to read the folder name "1"
                    String folderName = split[split.length - 2];

                    // If you want to read this file
                    // Read the file's content
                    // InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceURL);
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Ответы [ 3 ]

0 голосов
/ 26 февраля 2019

Вы также можете просто сделать следующее:

 File f = new File("static/foo/");
 File[] arr = f.listFiles();
 for (File file : arr) {
     if (file.isDirectory())
        System.out.println(file);
 }
0 голосов
/ 26 февраля 2019

Похоже, что это можно решить с помощью https://stackoverflow.com/a/3923685/7610371

"Основные" биты из ответа выше:

InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream(fooPath);
BufferedReader br = new BufferedReader(new InputStreamReader(resourceStream)) 
String resource;

while ((resource = br.readLine()) != null) {
    // ... resource is the next filename; you can add it to an array
    // or use it here
}
0 голосов
/ 26 февраля 2019

Я думаю, вы должны использовать FileUtils.

В частности, метод listFilesAndDirs с фильтром DirectoryFileFilter.

...