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

时间:2011-01-04 19:06:08

标签: java image swing file jar

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

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

但它不起作用。有没有人知道另一种方法呢?

4 个答案:

答案 0 :(得分:5)

要从资源或原始文件在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);
    }
}
  • 别忘了关闭你的溪流等

答案 1 :(得分:3)

这应该有用。

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

答案 2 :(得分:2)

通常,您无法直接获取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));

答案 3 :(得分:1)

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