我正在使用需要File()作为参数的库。将JarEntry转换为文件
文件我想通过这是一个我要打包带我的应用程序,为的.jar
的一部分,请问有什么办法到的JarEntry我从我的.jar内获得一个文件转换我可以通过的对象?
如果不是,我必须临时将资源复制到磁盘,哪里才是放置临时文件的最佳位置?
谢谢。
我正在使用需要File()作为参数的库。将JarEntry转换为文件
文件我想通过这是一个我要打包带我的应用程序,为的.jar
的一部分,请问有什么办法到的JarEntry我从我的.jar内获得一个文件转换我可以通过的对象?
如果不是,我必须临时将资源复制到磁盘,哪里才是放置临时文件的最佳位置?
谢谢。
您无法在JAR文件中获取文件的路径,只有流,因此您应该将其提取到临时目录,然后传递该提取的文件。 这是我写的一个函数,当我之前提供了一个带有jar的db时就这么做了。
/**
* 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;
}
}
A File
表示文件系统中的真实条目;文件系统上不存在JarEntry
。除非您将JAR条目提取到实际文件,否则该映射不会存在。
您可以使用File.createTempFile
创建临时文件。更多详情请见this SO answer。