将JarEntry转换为File

我正在使用一个想要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; } } 

File代表文件系统中的真实条目; 文件系统上不存在JarEntry 。 除非您将JAR条目提取到实际文件,否则映射将不存在。

您可以使用File.createTempFile创建临时文件。 有关详细信息,请参阅此SO答案 。