1

I'm trying to get system path, where jar is located in run time.

Below code works in REPL but, it fails if I assemble jar using sbt,

object tboj {
  def main(args: Array[String]) {
    def getCurrentDirectory = new java.io.File(".").getCanonicalPath
    val pwd = getCurrentDirectory
    println(pwd)
  }
}

SBT error as below,

run java.lang.RuntimeException: No main class detected. at scala.sys.package$.error(package.scala:27) [trace] Stack trace suppressed: run last compile:run for the full output. [error] (compile:run) No main class detected. [error] Total time: 0 s, completed 13 Apr, 2016 5:15:40 PM

WoodChopper
  • 4,265
  • 6
  • 31
  • 55
  • 2
    the error has nothing to do with the implementation of `main` - java can't _find_ the main function because the jar does not include the main-class attribute. See http://stackoverflow.com/questions/6467423/how-to-set-main-class-in-build for solutions. – Tzach Zohar Apr 13 '16 at 12:19

3 Answers3

3

If you want to find location of Jar using Class Name then use following way -

import org.apache.hadoop.fs.FileSystem
classOf[FileSystem].getProtectionDomain().getCodeSource().getLocation().toURI().getPath())

If you have instance, then use following way -

new ListBuffer[String]().getClass.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
Nikhil Bhide
  • 728
  • 8
  • 23
1

That will be System.getProperty("user.dir").

Worked for me for resolving native libs within my project.

Petro Semeniuk
  • 6,970
  • 10
  • 42
  • 65
  • That will get the user's home directory, which is not the same as the directory that the JAR file is located in of the running application. – Jesper Apr 13 '16 at 12:38
  • Nope, per https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html it's a user working directory, not a user home. – Petro Semeniuk Apr 13 '16 at 12:42
  • But that's still not what the OP is asking for, which is the location where the JAR of the running application is. – Jesper Apr 13 '16 at 12:42
0

try println(getClass.getProtectionDomain.getCodeSource.getLocation)

Renkai
  • 1,991
  • 2
  • 13
  • 18