0

Having this snippet of code:

val xml_folder_2 = getClass.getResource("xml-files")
val resourcePath = Paths.get(URLDecoder.decode(xml_folder_2.getFile, "UTF-8")).toString.replace("!","")
val dir_path = new File(resourcePath).listFiles.map(_.getPath)

Everything works perfectly until I want to run a jar file. The first line finds the desired directory, second one decodes some unnecessary stuff from the path, and the third one tries to find the directory and list the files inside. In case of IntelliJ compilation it works well, but once I run the jar file the error says:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "$this" is null

So it means that the program couldn't find "xml-files" (when I want to create new variable "dir_path" it fails). I tried to hardcode each step, and I noticed that the jar file sees the path to the desired directory e.g. /desktop/my_jar.jar/xml-files, but it still throws out the error.

Does anyone have an idea how to figure it out?

PS: I tried to hardcode the path inside "new File(path)" in many different ways, but it didn't help.

forvev
  • 5
  • 2
  • 1
    Does this answer your question? [Java resource as File](https://stackoverflow.com/questions/676097/java-resource-as-file) (look at the accepted answer) – Gaël J Mar 19 '23 at 11:10
  • The beginning was here https://stackoverflow.com/questions/75776876/reading-the-content-of-a-directory-in-scala – Dmytro Mitin Mar 19 '23 at 15:08

1 Answers1

1

Class::getResource() does not read a "file" (or does not provide the URL for a "file"), at least not as you would expect.

An instance of File lives in the file system of your machine, but a resource lives on the CLASSPATH of your program. As long as you did not create a Jar, this is the same (and Class::getResource() returns a file:// URL), but once you created the Jar, this is different (and the URL starts with jar://).

For the latter the handling of "directories" looks a little bit different than for regular files.

tquadrat
  • 3,033
  • 1
  • 16
  • 29