1

I am working with an external API which provides the following function:

public void process(File file) {
}

In my case, the file to be provided is in a JAR in the classpath. Is there a way to provide a File representing this file to process(File)?

I tried the following:

new File(getClass().getClassLoader().getResource("my-file.txt").toURI()))

This gives the error: URI is not hierarchical.

I did some researching and understood that files on the classpath should not be considered as a regular file, but as a resource. This makes me believe that there is no easy way to construct a File for that resource.

Should I copy the resource to a temporary file first?

TwentyFour
  • 13
  • 3

1 Answers1

1

Ideally, you'd fix the API, which is definitively broken. Otherwise, the only reliable way to get a File is to copy to a temporary one. You'll probably want to use Files.createTempDirectory and then something like Apache Commons IO IOUtils to copy the contents.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Thank you very much. So this means that I can only work with the API by creating a copy first? – TwentyFour Sep 25 '19 at 18:30
  • If this API requires an actual `File` object, then yes. This is _exactly_ why a `process` method should be using a `Reader` or `InputStream` instead. – chrylis -cautiouslyoptimistic- Sep 25 '19 at 18:34
  • 1
    Got it! I'll ask the API maintainer to add such method and in the meantime I'll work around it by creating a temporary file, in a temporary directory as you said. – TwentyFour Sep 25 '19 at 18:36
  • For a useful example, take a look at the various `readValue` signatures available in Jackson: https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/ObjectMapper.html – chrylis -cautiouslyoptimistic- Sep 25 '19 at 18:39
  • Those are useful. Appreciate the information! – TwentyFour Sep 25 '19 at 18:40
  • 1
    It would be useful if Guava or some other library has a convenient utility function for this :). I could work with IOUtilis as you said, but then I still have to create the directory, open and close an OutputStream and such. That said, it's better than having to do everything by hand. – TwentyFour Sep 25 '19 at 18:41