Reputation: 25865
How can I get the current directory (working directory) of the executing program in Scala?
Upvotes: 17
Views: 27815
Reputation: 87
You can find it using the system property user.dir
:
sys.props("user.dir")
Upvotes: 0
Reputation: 19328
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.
Upvotes: 2
Reputation: 978
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
Upvotes: 24
Reputation: 44957
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.
Upvotes: 17
Reputation: 2371
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
Upvotes: 5