How to load a resource using Class Loader as a file?

I want to open files using the class loader. However, I always get a FileNotFoundException. How to create a new file using url? I do not want to open it as a stream, as a file.

URL url = VersionUpdater.class.getResource("xslt/screen/foo"); File f = ... 
+4
source share
2 answers

To convert the file://... URL to java.io.File , you need to combine both url.getPath() and url.toURI() for a safe solution:

 File f; try { f = new File(url.toURI()); } catch(URISyntaxException e) { f = new File(url.getPath()); } 

Full explanation in this post.

+3
source

I just think: what if foo is in the bank? Then you could not create the file.

It should be possible to make it work if foo really is in the (local) class path directory - but you know that it won’t succeed if someone packs it in a jar or uploads it over the network ...

0
source

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


All Articles