Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use path of source in a scala script file

Tags:

file

path

scala

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.

like image 561
Wayne Jhukie Avatar asked Feb 20 '23 22:02

Wayne Jhukie


2 Answers

Script preamble:

#!/bin/sh
export SCRIPT_PATH=$(readlink -f "$0") && exec scala "$0" "$@"
!#

Read the value with:

val scriptPath = System.getenv("SCRIPT_PATH")
like image 146
Jamie Eisenhart Avatar answered Feb 26 '23 20:02

Jamie Eisenhart


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
like image 39
Connor Doyle Avatar answered Feb 26 '23 20:02

Connor Doyle