Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
MBU Avatar asked Dec 29 '22 03:12

MBU


1 Answers

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
like image 74
Blundell Avatar answered Jan 04 '23 16:01

Blundell