MBU
MBU

Reputation: 5098

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

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?

Upvotes: 4

Views: 14574

Answers (4)

Blundell
Blundell

Reputation: 76458

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

Upvotes: 4

mhaller
mhaller

Reputation: 14232

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

Upvotes: 2

Will
Will

Reputation: 6286

This should work.

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

Upvotes: 3

Konstantin Komissarchik
Konstantin Komissarchik

Reputation: 29139

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.

Upvotes: 1

Related Questions