4

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?

MBU
  • 4,998
  • 12
  • 59
  • 98

4 Answers4

4

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
Blundell
  • 75,855
  • 30
  • 208
  • 233
3

This should work.

String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Will
  • 6,179
  • 4
  • 31
  • 49
2

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));
mhaller
  • 14,122
  • 1
  • 42
  • 61
  • 1
    What package is FilenameUtils in? – MBU Jan 04 '11 at 20:27
  • 1
    Note that code snippet would not work for either an applet or an app. deployed using JWS. Unless the resource requires editing (unlikely with an image), expanding it to a temporary file is usually not the way to go. – Andrew Thompson Jan 05 '11 at 01:38
  • https://stackoverflow.com/questions/4301329/java-class-getresource-returns-null – the_prole Jun 05 '20 at 23:09
1

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.

Konstantin Komissarchik
  • 28,879
  • 6
  • 61
  • 61
  • 1
    "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." Specifically, you can use `getResourceAsStream` instead of `getResource` – Powerlord Jan 04 '11 at 19:14