Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading files from JAR in Scala

Tags:

jar

scala

I have the following code structure:

Projects/
     classes/
         performance/AcPerformance.class
         resources/
                  Aircraft/
                          allAircraft.txt

I have the contents of the classes folder in a JAR and my AcPerformance scala code is trying to read the contents of the Aircraft folder text files. My code:

val AircraftPerf = getClass.getResource("resources/Aircraft").getFile
val dataDir = new File(AircraftPerf)
val acFile = new File(dataDir, "allAircraft.txt")

for (line <- linesFromResource(acFile)) {
  // read in lines
}

When I try to run the code I get the following error:

Caused by: java.io.FileNotFoundException: C:\Projects\file:\C:\Projects\libraries\aircraft.jar!\Aircraft\allAircraft.txt (The filename, directory name, or volume label syntax is incorrect)

Is this the correct way to read the contents of a JAR? THanks!

like image 342
John Avatar asked Apr 20 '12 02:04

John


1 Answers

No, URL's getFile isn't going to do what you want here—the path it gives you isn't a file system path that you could use in a File constructor. You'd be best off using getResourceAsStream and the full path to the resource:

val in = getClass.getResourceAsStream("/resources/Aircraft/allAircraft.txt")

Note that you also need to preface the path with / to make it absolute—in your current version you're looking for a resources directory under performance.

like image 190
Travis Brown Avatar answered Oct 31 '22 02:10

Travis Brown