从jar中读取资源文件

问题描述 投票:179回答:13

我想从我的jar中读取资源,如下所示:

File file;
file = new File(getClass().getResource("/file.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));

//Read the file

并且它在Eclipse中运行时工作正常,但是如果我将它导出到jar,那么运行它就会出现IllegalArgumentException:

Exception in thread "Thread-2"
java.lang.IllegalArgumentException: URI is not hierarchical

而且我真的不知道为什么,但经过一些测试我发现如果我改变了

file = new File(getClass().getResource("/file.txt").toURI());

file = new File(getClass().getResource("/folder/file.txt").toURI());

然后它的工作正好相反(它适用于jar而不是eclipse)。

我正在使用Eclipse,我的文件夹在一个类文件夹中。

java file jar resources embedded-resource
13个回答
329
投票

而不是试图作为File解决资源只是要求ClassLoader返回InputStream资源,而不是通过getResourceAsStream

InputStream in = getClass().getResourceAsStream("/file.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

只要file.txt资源在类路径上可用,那么无论file.txt资源是在classes/目录中还是在jar内,这种方法都将以相同的方式工作。

发生URI is not hierarchical是因为jar文件中资源的URI看起来像这样:file:/example.jar!/file.txt。您无法读取jarzip文件)中的条目,就像它是一个普通的旧File

这可以通过以下答案得到很好的解释:


0
投票

如果您使用的是spring,那么您可以使用以下方法从src / main / resources中读取文件:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.core.io.ClassPathResource;

  public String readFileToString(String path) throws IOException {

    StringBuilder resultBuilder = new StringBuilder("");
    ClassPathResource resource = new ClassPathResource(path);

    try (
        InputStream inputStream = resource.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

      String line;

      while ((line = bufferedReader.readLine()) != null) {
        resultBuilder.append(line);
      }

    }

    return resultBuilder.toString();
  }

0
投票

由于某种原因,当我将Web应用程序部署到WildFly 14时,classLoader.getResource()总是返回null。从getClass().getClassLoader()Thread.currentThread().getContextClassLoader()获取classLoader将返回null。

getClass().getClassLoader() API doc说,

“返回类的类加载器。一些实现可能使用null来表示引导类加载器。如果此类由引导类加载器加载,则此方法将在此类实现中返回null。”

如果你使用WildFly和你的web应用程序可能会尝试这个

request.getServletContext().getResource()返回了资源网址。这里的请求是ServletRequest的一个对象。


0
投票

问题是某些第三方库需要文件路径名而不是输入流。大多数答案都没有解决这个问题。

在这种情况下,一种解决方法是将资源内容复制到临时文件中。以下示例使用jUnit的TemporaryFolder

    private List<String> decomposePath(String path){
        List<String> reversed = Lists.newArrayList();
        File currFile = new File(path);
        while(currFile != null){
            reversed.add(currFile.getName());
            currFile = currFile.getParentFile();
        }
        return Lists.reverse(reversed);
    }

    private String writeResourceToFile(String resourceName) throws IOException {
        ClassLoader loader = getClass().getClassLoader();
        InputStream configStream = loader.getResourceAsStream(resourceName);
        List<String> pathComponents = decomposePath(resourceName);
        folder.newFolder(pathComponents.subList(0, pathComponents.size() - 1).toArray(new String[0]));
        File tmpFile = folder.newFile(resourceName);
        Files.copy(configStream, tmpFile.toPath(), REPLACE_EXISTING);
        return tmpFile.getAbsolutePath();
    }

0
投票

下面的代码适用于Spring boot(kotlin):

val authReader = InputStreamReader(javaClass.getResourceAsStream("/file1.json"))

16
投票

要访问jar中的文件,您有两个选择:

  • 将文件放在与包名匹配的目录结构中(在解压缩.jar文件后,它应该与.class文件在同一目录中),然后使用getClass().getResourceAsStream("file.txt")访问它
  • 将文件放在根目录(提取.jar文件后,它应该在根目录中),然后使用Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt")访问它

当jar用作插件时,第一个选项可能不起作用。


5
投票

如果你想读作文件,我相信仍有类似的解决方案:

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("file/test.xml").getFile());

3
投票

之前我遇到过这个问题,我做了后备加载方式。基本上第一种方式在.jar文件中工作,第二种方式在eclipse或其他IDE中工作。

public class MyClass {

    public static InputStream accessFile() {
        String resource = "my-file-located-in-resources.txt";

        // this is the path within the jar file
        InputStream input = MyClass.class.getResourceAsStream("/resources/" + resource);
        if (input == null) {
            // this is how we load file within editor (eg eclipse)
            input = MyClass.class.getClassLoader().getResourceAsStream(resource);
        }

        return input;
    }
}

1
投票

确保使用正确的分隔符。我用/替换了相对路径中的所有File.separator。这在IDE中运行良好,但在构建JAR中不起作用。


1
投票

到目前为止(2017年12月),这是我发现的唯一可在IDE内部和外部工作的解决方案。

使用PathMatchingResourcePatternResolver

注意:它也适用于spring-boot

在这个例子中,我正在读取位于src / main / resources / my_folder中的一些文件:

try {
    // Get all the files under this inner resource folder: my_folder
    String scannedPackage = "my_folder/*";
    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources = scanner.getResources(scannedPackage);

    if (resources == null || resources.length == 0)
        log.warn("Warning: could not find any resources in this scanned package: " + scannedPackage);
    else {
        for (Resource resource : resources) {
            log.info(resource.getFilename());
            // Read the file content (I used BufferedReader, but there are other solutions for that):
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                // ...
                // ...                      
            }
            bufferedReader.close();
        }
    }
} catch (Exception e) {
    throw new Exception("Failed to read the resources folder: " + e.getMessage(), e);
}

0
投票

经过大量的Java挖掘后,唯一对我有用的解决方案是手动读取jar文件本身,除非你在开发环境(IDE)中:

/** @return The root folder or jar file that the class loader loaded from */
public static final File getClasspathFile() {
    return new File(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile());
}

/** @param resource The path to the resource
 * @return An InputStream containing the resource's contents, or
 *         <b><code>null</code></b> if the resource does not exist */
public static final InputStream getResourceAsStream(String resource) {
    resource = resource.startsWith("/") ? resource : "/" + resource;
    if(getClasspathFile().isDirectory()) {//Development environment:
        return YourMainClass.class.getResourceAsStream(resource);
    }
    final String res = resource;//Jar or exe:
    return AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
        @SuppressWarnings("resource")
        @Override
        public InputStream run() {
            try {
                final JarFile jar = new JarFile(getClasspathFile());
                String resource = res.startsWith("/") ? res.substring(1) : res;
                if(resource.endsWith("/")) {//Directory; list direct contents:(Mimics normal getResourceAsStream("someFolder/") behaviour)
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    Enumeration<JarEntry> entries = jar.entries();
                    while(entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        if(entry.getName().startsWith(resource) && entry.getName().length() > resource.length()) {
                            String name = entry.getName().substring(resource.length());
                            if(name.contains("/") ? (name.endsWith("/") && (name.indexOf("/") == name.lastIndexOf("/"))) : true) {//If it's a folder, we don't want the children's folders, only the parent folder's children!
                                name = name.endsWith("/") ? name.substring(0, name.length() - 1) : name;
                                baos.write(name.getBytes(StandardCharsets.UTF_8));
                                baos.write('\r');
                                baos.write('\n');
                            }
                        }
                    }
                    jar.close();
                    return new ByteArrayInputStream(baos.toByteArray());
                }
                JarEntry entry = jar.getJarEntry(resource);
                InputStream in = entry != null ? jar.getInputStream(entry) : null;
                if(in == null) {
                    jar.close();
                    return in;
                }
                final InputStream stream = in;//Don't manage 'jar' with try-with-resources or close jar until the
                return new InputStream() {//returned stream is closed(closing the jar closes all associated InputStreams):
                    @Override
                    public int read() throws IOException {
                        return stream.read();
                    }

                    @Override
                    public int read(byte b[]) throws IOException {
                        return stream.read(b);
                    }

                    @Override
                    public int read(byte b[], int off, int len) throws IOException {
                        return stream.read(b, off, len);
                    }

                    @Override
                    public long skip(long n) throws IOException {
                        return stream.skip(n);
                    }

                    @Override
                    public int available() throws IOException {
                        return stream.available();
                    }

                    @Override
                    public void close() throws IOException {
                        try {
                            jar.close();
                        } catch(IOException ignored) {
                        }
                        stream.close();
                    }

                    @Override
                    public synchronized void mark(int readlimit) {
                        stream.mark(readlimit);
                    }

                    @Override
                    public synchronized void reset() throws IOException {
                        stream.reset();
                    }

                    @Override
                    public boolean markSupported() {
                        return stream.markSupported();
                    }
                };
            } catch(Throwable e) {
                e.printStackTrace();
                return null;
            }
        }
    });
}

注意:上面的代码似乎只适用于jar文件,如果它在主类中。我不知道为什么。


0
投票

你可以使用类加载器,它将从类路径读取为ROOT路径(开头没有“/”)

InputStream in = getClass().getClassLoader().getResourceAsStream("file.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

0
投票

我认为这应该也适用于java。我使用的以下代码是使用kotlin。

val resource = Thread.currentThread().contextClassLoader.getResource('resources.txt')
© www.soinside.com 2019 - 2024. All rights reserved.