How to get the current (working) directory in Scala?

13,785

Solution 1

Use this System.getProperty("user.dir")

Edit: A list of other standard properties can be found here. https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Solution 2

Use java.nio:

import java.nio.file.Paths
println(Paths.get(".").toAbsolutePath)

Remark on scala.reflect.io.File: I don't see any reason to look into scala.reflect packages for such mundane tasks. Getting the current working directory has usually nothing to do with Scala's reflection capabilities. Here are more reasons not to use scala.reflect.io.File: link.

Solution 3

I use new java.io.File(".").getAbsolutePath, but all the other answers work too. You don't really gain anything by using Scala-specific API here over regular Java APIs

Solution 4

Use this:

import scala.reflect.io.File
File(".").toAbsolute

Solution 5

import scala.sys.process._
val cwd = "pwd".!!  //*nix OS
Share:
13,785
Neil
Author by

Neil

Updated on June 05, 2022

Comments

  • Neil
    Neil about 2 years

    How can I get the current directory (working directory) of the executing program in Scala?

  • AlainD
    AlainD over 5 years
    If the response is correct, please accept the answer, so other can benefit from it. (A moderator)
  • Jake
    Jake over 4 years
    This seems the "most" correct answer of the answers provided, as it's a standard java property and therefore doesn't require the developer know what "." means (although all developers probably do). The java docs provide a definition for the property here: docs.oracle.com/javase/tutorial/essential/environment/…
  • Pubudu Sitinamaluwa
    Pubudu Sitinamaluwa almost 4 years
    updated the answer with the link provided by @jake. Thanks.
  • Sam Mefford
    Sam Mefford about 3 years
    When I tried this in Spark Scala in an EMR Notebook, I got cwd: String = "/ " which means it's not helping me see the absolute path...
  • uxke
    uxke almost 3 years
    have not managed to get the import part working. Added the lib to build.sbt and os is visible in external libraries but importing that to code is not working. How do you do it?
  • Powers
    Powers almost 3 years
    @juske - you shouldn't need to import anything. The code is in the os package, so os.pwd is the full path. You might just need to reload IntelliJ as you would whenever a dependency is added to the build.sbt file.
  • uxke
    uxke almost 3 years
    thanks for quick reply! still getting an error: not found: value os although there is sbt: com.lihaoyi:os-lib_2.13:0.78.jar under external libraries