I am looking for a way to use the full path of the *.scala file that is executed by
scala /path/to/file/file.scala
The reason is that within my script I would like to use paths, which are relative to the location where file.scala is saved. So, say I want to call /path/to/file/file_second.scala from inside of file.scala while calling file.scala by
scala ./to./file/file.scala
as the directory I invoked scala from is /path (i.e. what System.getProperty("user.dir") would return). All I know priori is that file_second.scala is in the same directory as file.scala without actually knowing the full path.
I have tried. among others, getClass.getResource("").split(":")(1), but this will either return /path/./ or /tmp/scala.tmp/
I guess there must be a clean solution as scala -savecompiled will create a *.jar at exactly that directory I want to work on, but I just cannot figure out how... :/
Many thanks for any help.
Script preamble:
#!/bin/sh
export SCRIPT_PATH=$(readlink -f "$0") && exec scala "$0" "$@"
!#
Read the value with:
val scriptPath = System.getenv("SCRIPT_PATH")
I've done this in the past in Java. It's not pretty, and it may not be 100% reliable depending on the details of your class loader situation.
Here is some Scala code that prints out the location of its own class file.
import java.net.URL
object LocationTest extends App {
val classDirURL = LocationTest.getClass.getResource("LocationTest.class")
val classDirPath = classDirURL.getPath.replaceAll("%20", " ")
println(classDirPath)
}
prints
/Users/connor/desktop/LocationTest.class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With