从资源路径创建一个文件对象到一个jar文件中的图像 [英] Create a file object from a resource path to an image in a jar file

查看:186
本文介绍了从资源路径创建一个文件对象到一个jar文件中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个jar文件后,我需要从一个文件路径创建一个File对象到一个包含在jar文件中的图像。如果尝试使用:

  URL url = getClass()。getResource(/ resources / images / image.jpg); 
File imageFile = new File(url.toURI());

但是不起作用。有没有人知道另一种方法呢?通常情况下,你不能直接得到一个的解决方案。

java.io.File 对象,因为压缩归档文件中没有物理文件。要么你住在一个流(这是最好的,因为每个好的API都可以使用流),或者你可以创建一个临时文件:

  URL imageResource = getClass()。getResource(image.gif); 
File imageFile = File.createTempFile(
FilenameUtils.getBaseName(imageResource.getFile()),
FilenameUtils.getExtension(imageResource.getFile()));
IOUtils.copy(imageResource.openStream(),
FileUtils.openOutputStream(imageFile));


I need to create a File object out of a file path to an image that is contained in a jar file after creating a jar file. If tried using:

URL url = getClass().getResource("/resources/images/image.jpg");
File imageFile = new File(url.toURI());

but it doesn't work. Does anyone know of another way to do it?

解决方案

Usually, you can't directly get a java.io.File object, since there is no physical file for an entry within a compressed archive. Either you live with a stream (which is best most in the cases, since every good API can work with streams) or you can create a temporary file:

    URL imageResource = getClass().getResource("image.gif");
    File imageFile = File.createTempFile(
            FilenameUtils.getBaseName(imageResource.getFile()),
            FilenameUtils.getExtension(imageResource.getFile()));
    IOUtils.copy(imageResource.openStream(),
            FileUtils.openOutputStream(imageFile));

这篇关于从资源路径创建一个文件对象到一个jar文件中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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