java - 将 jar 文件 URI 转换为文件

标签 java jar embedded-resource

我需要从 Jar 中访问配置文件,因此我使用:

URL configUrl = Object.class.getResource("/config.xml");

现在我需要将 URL 转换为 File 对象,因为这是下游 ConfigurationFile 对象初始化所需的。当我尝试这个时:

new File(configUrl.toURI())

我得到:

 java.lang.IllegalArgumentException: URI is not hierarchical

当我尝试这个时:

 new File(Thread.currentThread().getContextClassLoader().getResource("config.xml").getFile())

我得到:

File does not exist: 'file:\E:\Apps\jarfile.jar!\config.xml'

注意:不幸的是,我必须在 InputStream 上有一个 File 对象。

最佳答案

如果文件位于 JAR 内部...您可以使用 getResourceAsStream() 并直接读取或使用 URL...

URL urlConfig = Object.class.getResource(CONFIG_FILE);
if (urlConfig == null) {
    // throw <error>
}
URLConnection connConfig = urlConfig.openConnection();
InputStream isConfig = connConfig.getInputStream(); // do things

将内容保存到临时文件...(等待 1 秒...嗯)

public static File doThing(InputStream is) throws IOException {
    File tmp = null;
    FileOutputStream tmpOs = null;
    try {
        tmp = File.createTempFile("xml", "tmp");
        tmpOs = new FileOutputStream(tmp);
        int len = -1;
        byte[] b = new byte[4096];
        while ((len = is.read(b)) != -1) {
            tmpOs.write(b, 0, len);
        }
    } finally {
        try { is.close(); } catch (Exception e) {}
        try { tmpOs.close(); } catch (Exception e) {}
    }
    return tmp;
}

关于java - 将 jar 文件 URI 转换为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14180499/

相关文章:

java - 语法错误: Unexpected token ILLEGAL in Node Javascript

java - 正在运行的线程可以看到私有(private)字段的变化吗?

java命令创建奇怪的PID日志文件

java - Spring WS : Handle connection refused and client timeout exceptions

java - Spring-security 与 spring-4.3.0-release 的兼容版本是什么?

java - 如何授予 jar 文件以执行另一个 jar 文件

java - float 数组到 double 数组

flash - 字体未嵌入 Flash CS4 AS3

具有通用资源的 Android 库

java - 在 jar 中加载字体作为资源失败