2

I have a Resource object (org.springframework.core.io.ClassPathResource). I need to get File object, but resource.getFile() throws an exeption File not Found. but after invoking resource.getURI() I have a result

jar:file:/D: .... file.jar!/com//test/0be14958-3778-40bf-bd3e-ee605fcdd3f0/verify

Directory is located in jar file. Is it possible to workaround limitation for ClassPathResource and create a File object?

I've tried a new File(resource.getURI()) but it fails with java.lang.IllegalArgumentException: URI is not hierarchical

what is my fault?

Constantine Gladky
  • 1,245
  • 6
  • 27
  • 45

1 Answers1

5

I don't think it's possible to get a java.io.File out of something that's in a JAR (because it's not actually a file). From the ClassPathResource JavaDoc:

Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR.

You don't mention why you need it as a java.io.File, but maybe you can refactor your code to use the ClassPathResource.getInputStream method (which enables you to read the resource)?

Either that or you could also use ClassPathResource.getInputStream to copy the file you want to a temporary file on the file system that you could then use as a straight up java.io.File.

File temp = File.createTempFile("temp", ".tmp");
org.apache.commons.io.IOUtils.copy(resource.getInputStream(), new FileOutputStream(temp));
Christophe L
  • 13,725
  • 6
  • 33
  • 33
  • I need File to invoke list() method to get names of subdirectories in it. – Constantine Gladky Nov 22 '12 at 08:58
  • Unfortunately I get NPE on org.apache.commons.io.IOUtils.copy. Both objects resource.getInputStream() and new FileOutputStream(temp) are not null. – Constantine Gladky Nov 22 '12 at 08:59
  • Ah... What I said should work for a file in a JAR but not for a directory. If you need to list the content of a directory in a JAR you might need to go a different route. A JAR file is just a regular zip file, so you can parse the path to it from getURI (the part before the "!") and open it as described [here](http://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file). – Christophe L Nov 23 '12 at 19:22
  • The [Util class in MariaDB4j has a ready-made extractFromClasspathToFile() method](https://github.com/vorburger/MariaDB4j/blob/master/src/main/java/ch/vorburger/mariadb4j/Util.java) which you may find useful. - BTW, also an example how to, with correct unique temporary filename, e.g. in Mifos' [EmbeddedTomcatWithSSLConfiguration.java](https://github.com/vorburger/mifosx/blob/990f71a30a70d44cb7216f0d9594b1fd80ba779c/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/boot/EmbeddedTomcatWithSSLConfiguration.java) – vorburger Sep 21 '14 at 22:32