Create a file object from a resource path to an image in a jar file

14,089

Solution 1

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

Solution 2

To create a file on Android from a resource or raw file I do this:

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);
    }
}
  • Don't forget to close your streams etc

Solution 3

This should work.

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

Solution 4

You cannot create a File object to a reference inside an archive. If you absolutely need a File object, you will need to extract the file to a temporary location first. On the other hand, most good API's will also take an input stream instead, which you can get for a file in an archive.

Share:
14,089
MBU
Author by

MBU

Updated on June 18, 2022

Comments

  • MBU
    MBU almost 2 years

    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?