How can I get the current directory (working directory) of the executing program in Scala?
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
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.
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
Use this:
import scala.reflect.io.File
File(".").toAbsolute
File(".").toCanonical
instead. –
Shelby import scala.sys.process._
val cwd = "pwd".!! //*nix OS
cwd: String = "/ "
which means it's not helping me see the absolute path... –
Belshazzar os-lib makes it easy to get the current working directory and perform other filesystem operations. Here's how to get the current directory:
os.pwd
It's easy to build other path objects from os.pwd
, for example:
os.pwd/"src"/"test"/"resources"/"people.csv"
The syntax is intuitive and easy to remember, unlike the other options. See here for more details on how to use the os-lib project.
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. –
Government error: not found: value os
although there is sbt: com.lihaoyi:os-lib_2.13:0.78.jar
under external libraries –
Townscape © 2022 - 2024 — McMap. All rights reserved.