我需要从 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/