Creating a file object from the resource path to the image in the jar file

I need to create a File object from the file path that is contained in the jar file after creating the jar file. If you try to use:

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

but that will not work. Does anyone know how to do this?

+4
source share
4 answers

Usually you cannot directly get the java.io.File object, since there is no physical file to write to the compressed archive. Either you live with a stream (which is best in such 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)); 
+2
source

To create an Android file from a resource or a 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); } } 
  • Remember to close your threads, etc.
+5
source

That should work.

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

You cannot create a File object for a link inside an archive. If you absolutely need a File object, you first need to extract the file to a temporary location. On the other hand, for most good APIs, you will also need the input stream that you can get for the file in the archive.

+1
source

Source: https://habr.com/ru/post/1334254/


All Articles