【发布时间】:2013-07-27 23:44:22
【问题描述】:
我正在使用一个需要 File() 作为参数的库。
我要传递的文件是我想与我的应用一起打包的文件,作为 .jar 的一部分
有什么方法可以将我从 .jar 中获取的 JarEntry 转换为我可以传递的 File 对象?
如果没有,我必须将资源临时复制到磁盘,放置临时文件的最佳位置是哪里?
谢谢。
【问题讨论】:
标签: java jar executable-jar
我正在使用一个需要 File() 作为参数的库。
我要传递的文件是我想与我的应用一起打包的文件,作为 .jar 的一部分
有什么方法可以将我从 .jar 中获取的 JarEntry 转换为我可以传递的 File 对象?
如果没有,我必须将资源临时复制到磁盘,放置临时文件的最佳位置是哪里?
谢谢。
【问题讨论】:
标签: java jar executable-jar
您无法在 JARFile 中获取文件的路径,只能获取流,因此您应该将其提取到临时目录,然后传递提取的文件。 这是我之前为 db 提供 jar 时编写的一个函数。
/**
* This method is responsible for extracting resource files from within the .jar to the temporary directory.
* @param filePath The filepath relative to the 'Resources/' directory within the .jar from which to extract the file.
* @return A file object to the extracted file
**/
public File extract(String filePath)
{
try
{
File f = File.createTempFile(filePath, null);
FileOutputStream resourceOS = new FileOutputStream(f);
byte[] byteArray = new byte[1024];
int i;
InputStream classIS = getClass().getClassLoader().getResourceAsStream("Resources/"+filePath);
//While the input stream has bytes
while ((i = classIS.read(byteArray)) > 0)
{
//Write the bytes to the output stream
resourceOS.write(byteArray, 0, i);
}
//Close streams to prevent errors
classIS.close();
resourceOS.close();
return f;
}
catch (Exception e)
{
System.out.println("An error has occurred while extracting the database. This may mean the program is unable to have any database interaction, please contact the developer.\nError Description:\n"+e.getMessage());
return null;
}
}
【讨论】:
File 代表文件系统中的真实条目;文件系统上不存在 JarEntry。除非您将 JAR 条目提取到实际文件中,否则映射不会存在。
您可以使用File.createTempFile 创建一个临时文件。更多详情请访问this SO answer。
【讨论】: