gpt4 book ai didi

java - 将 JarEntry 转换为文件

转载 作者:行者123 更新时间:2023-11-30 06:23:47 25 4
gpt4 key购买 nike

我正在使用一个需要 File() 作为参数的库。

我要传递给它的文件是我想与我的应用程序一起打包的文件,作为 .jar 的一部分

有什么方法可以将从我的 .jar 中获取的 JarEntry 转换为我可以传递的 File 对象?

如果没有,我必须临时将资源复制到磁盘,放置临时文件的最佳位置在哪里?

谢谢。

最佳答案

您无法获取 JARFile 中文件的路径,只能获取流,因此您应该将其提取到临时目录,然后传递提取的文件。这是我之前为数据库提供 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;
}
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com