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
Author by
Neil
Updated on June 05, 2022Comments
-
Neil about 2 years
How can I get the current directory (working directory) of the executing program in Scala?
-
AlainD over 5 yearsIf the response is correct, please accept the answer, so other can benefit from it. (A moderator)
-
Jake over 4 yearsThis 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 almost 4 yearsupdated the answer with the link provided by @jake. Thanks.
-
Sam Mefford about 3 yearsWhen 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 almost 3 yearshave 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 almost 3 years@juske - you shouldn't need to import anything. The code is in the
os
package, soos.pwd
is the full path. You might just need to reload IntelliJ as you would whenever a dependency is added to thebuild.sbt
file. -
uxke almost 3 yearsthanks for quick reply! still getting an
error: not found: value os
although there issbt: com.lihaoyi:os-lib_2.13:0.78.jar
under external libraries