0

I have written Scala program that is reading some data from file.

lazy val vectorOptF2 = Source.fromFile("DataFiles/F2-xopt.txt").getLines().map(_.toDouble). toList

When I execute my code in IntelliJ IDEA IDE, It run successfully. But when I created JAR file

mvn clean packae

and tried to execute JAR file, it throws error stating so such file found.

Exception in thread "main" java.io.FileNotFoundException: DataFiles/F2-xopt.txt (No such file or directory)

I have created ZIP file DataFiles.zip and move it to JAR file

mv DataFiles.zip MyJar.jar

but same was error. How can I read data from files placed inside a folder in JAR file?

  • There are multiple files in side Folder DataFiles and have to read some of them based on specified criteria each time program executes.
Asif
  • 763
  • 8
  • 18
  • 2
    If the file is inside the **JAR**, it is not longer a file but a resource, you need something like: `Source.fromInputStream(Thread.currentThread.getContextClassLoader.getResourceAsStream("foo/bar"))` – Luis Miguel Mejía Suárez Jul 11 '20 at 20:04

1 Answers1

2

If you are following EAR structure, add your data files after creating respective directory structures in the src/main/resources/ directory and read it using the following code.

lazy val vectorOptF2 = Source.fromResource
("DataFiles/F2-xopt.txt").getLines().map(_.toDouble). toList
sathya
  • 1,982
  • 1
  • 20
  • 37
  • 2
    The `fromFile` will not open a resource. You need `getResourceAsStream` or `Source.fromResource` for that. See https://stackoverflow.com/questions/27360977/how-to-read-files-from-resources-folder-in-scala – Suma Jul 12 '20 at 07:07
  • @Suma, Updated my answer as per your comments. – sathya Jul 12 '20 at 07:11