获取jar包内指定资源文件方法

194 阅读1分钟

在 Java 中,如果你想从 JAR 文件中获取特定的文件,通常使用 ClassLoader 来查找资源。以下是如何从 JAR 文件中获取指定文件的几种常见方法:

使用 ClassLoader.getResourceAsStream()

这是最常用的方法之一,适用于从类路径中加载资源文件,无论这些文件是在 JAR 内还是在文件系统中。

import java.io.InputStream;
import java.io.IOException;

public class JarResourceLoader {
    public static void main(String[] args) {
        // 假设你想要获取 JAR 文件中的 "config.properties"
        String resourcePath = "config.properties";

        // 使用当前类的类加载器
        try (InputStream inputStream = JarResourceLoader.class.getClassLoader().getResourceAsStream(resourcePath)) {
            if (inputStream == null) {
                System.out.println("Resource not found: " + resourcePath);
                return;
            }

            // 读取文件内容
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);

            String content = new String(buffer);
            System.out.println("Resource content: \n" + content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 ClassLoader.getResource()

如果你需要获取资源的 URL 而不是直接读取其内容,可以使用 getResource() 方法。

import java.net.URL;

public class JarResourceURLLoader {
    public static void main(String[] args) {
        String resourcePath = "config.properties";

        // 使用当前类的类加载器
        URL resourceUrl = JarResourceURLLoader.class.getClassLoader().getResource(resourcePath);
        if (resourceUrl != null) {
            System.out.println("Resource URL: " + resourceUrl);
            InputStream input = resourceUrl.openStream()
        } else {
            System.out.println("Resource not found: " + resourcePath);
        }
    }
}

注意事项

  1. 资源路径:资源路径是相对于类路径的,不应该以 / 开头。例如,"config.properties" 而不是 "/config.properties"

  2. 类加载器:使用合适的类加载器非常重要。通常使用当前类的类加载器(getClass().getClassLoader())或系统类加载器(ClassLoader.getSystemClassLoader())。

  3. 资源可见性:确保资源在你的类路径中可访问。如果资源在某个 JAR 文件中,该 JAR 文件需要在运行时的类路径中。

  4. 关闭流:使用 getResourceAsStream() 时,记得在使用完毕后关闭流。使用 try-with-resources 语句可以自动关闭流。

通过这些方法,你可以方便地从 JAR 文件中获取和读取特定的资源文件。