Neil
Neil

Reputation: 25865

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

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

Upvotes: 17

Views: 27815

Answers (7)

Spearmint
Spearmint

Reputation: 87

You can find it using the system property user.dir:

sys.props("user.dir")

Upvotes: 0

Powers
Powers

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

Pubudu Sitinamaluwa
Pubudu Sitinamaluwa

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

Andrey Tyukin
Andrey Tyukin

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

Alex Savitsky
Alex Savitsky

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

jwvh
jwvh

Reputation: 51271

import scala.sys.process._
val cwd = "pwd".!!  //*nix OS

Upvotes: 4

Neil
Neil

Reputation: 25865

Use this:

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

Upvotes: 4

Related Questions