从资源路径创建文件对象到jar文件中的图像

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

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)); 

要从资源或原始文件在Android上创建文件,我执行以下操作:

 try{ InputStream inputStream = getResources().openRawResource(R.raw.some_file); File tempFile = File.createTempFile("pre", "suf"); copyFile(inputStream, new FileOutputStream(tempFile)); // Now some_file is tempFile .. do what you like } catch (IOException e) { throw new RuntimeException("Can't create temp file ", e); } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } } 
  • 别忘了关闭你的溪流等

这应该工作。

 String imgName = "/resources/images/image.jpg"; InputStream in = getClass().getResourceAsStream(imgName); ImageIcon img = new ImageIcon(ImageIO.read(in)); 

您无法为归档内的引用创建File对象。 如果您绝对需要File对象,则需要先将文件解压缩到临时位置。 另一方面,大多数优秀的API也将采用输入流,您可以获取存档中的文件。