将JarEntry转换为File [英] Convert JarEntry to File

查看:790
本文介绍了将JarEntry转换为File的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using a library which wants a File() as an argument.

我要传递的文件是我要用我的app打包的文件,作为.jar的一部分

The file I want to pass it is one I want to package with my app, as part of the .jar

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

Is there any way to convert the JarEntry that I get from within my .jar to a File object I can pass?

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

If not and I have to copy the resource to disk temporarily, where's the best place to put the temporary file?

谢谢。

推荐答案

您无法获取JARFile中的文件路径,只能获取流,因此您应该将其提取到临时目录,然后传递该提取的文件。
这是我写的一个函数,当我之前提供带有jar的数据库时。

You cannot get a path to a file within a JARFile, only a stream, so you should extract it to the temporary directory and then pass that extracted file. Here's a function I wrote to do this when I provided a db with a jar previously.

/**
*  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;
    }
}

这篇关于将JarEntry转换为File的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆