Список файлов из каталога classpath в запущенном jar - PullRequest
0 голосов
/ 11 мая 2018

Я хочу загрузить все свойства пакета ресурсов из classpath, чтобы я мог показывать поддерживаемые языки. Я получил ссылку от здесь и попробовал 1-е решение. Это работает файл, когда я запускаю свой код из затмения. Но когда я создавал исполняемый файл JAR, он не мог читать файлы. Я не знаю, почему при запуске из команды java -jar AppName.jar

поведение отличается

Мой код:

public static List<String> getResourceFiles(String path) throws IOException
{
    List<String> filenames = new ArrayList<>();

    InputStream in = getResourceAsStream(path);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    System.out.println("br = " + br.readLine());
    String resource;
    while ((resource = br.readLine()) != null)
    {
        filenames.add(resource);
    }

    return filenames;
}

private static InputStream getResourceAsStream(String resource)
{
    final InputStream in = getContextClassLoader().getResourceAsStream(resource);
    System.out.println("input stream = " + in);

    return in == null ? FileUtil.class.getResourceAsStream(resource) : in;
}

private static ClassLoader getContextClassLoader()
{
    return Thread.currentThread().getContextClassLoader();
}

Здесь я заметил, что InputStream имеет значение null, когда я запускаю из команды, но при запуске из eclipse InputStream не имеет значение null.

Как решить эту проблему, чтобы я мог читать файлы ресурсов при запуске из команды?

Ответы [ 2 ]

0 голосов
/ 17 мая 2018

Я нашел решение.Ниже код работал для меня:

public static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException
{
    URL dirURL = clazz.getClassLoader().getResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file"))
    {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }

    if (dirURL == null)
    {
        /*
         * In case of a jar file, we can't actually find a directory. Have to assume the
         * same jar as clazz.
         */
        String me = clazz.getName().replace(".", "/") + ".class";
        dirURL = clazz.getClassLoader().getResource(me);
    }

    if (dirURL.getProtocol().equals("jar"))
    {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); // strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
        Set<String> result = new HashSet<String>(); // avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements())
        {
            String name = entries.nextElement().getName();
            if (name.startsWith(path))
            { // filter according to the path
                String entry = name.substring(path.length());
                int checkSubdir = entry.indexOf("/");
                if (checkSubdir >= 0)
                {
                    // if it is a subdirectory, we just return the directory name
                    entry = entry.substring(0, checkSubdir);
                }
                result.add(entry);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
0 голосов
/ 11 мая 2018

Я думаю, что вы можете добавить свой путь к приложению в системную среду (classpath), если не можете решить вашу проблему, попробуйте распечатать реальный путь перед инициализацией файлового потока и исправить это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...