Depending on your needs there are a couple of ways to get the current working directory in a Scala application.
1) Using System.getProperty
The most obvious/direct approach is to use the Java System.getProperty
method, passing in "user.dir"
as a parameter:
System.getProperty("user.dir")
I’ve used this technique in Scala command-line scripts and GUI applications (Swing and JavaFX) and I can confirm that this approach works. You can test this easily by moving to a random directory, starting up the Scala REPL, and then running that line of code. I just did that, and it works as expected, returning the full (canonical) path to my current directory.
2) Using java.io.File.getCanonicalPath
Another approach to getting the current working directory in a Scala application is to use the Java File
class, like this:
val currentDirectory = new java.io.File(".").getCanonicalPath
I just tested that approach in the Scala REPL and it also works as expected, returning the full path to the current directory.
Discussion
A long time ago I wrote about How to get the current directory in Java, and after I wrote that some people commented that it didn’t work as expected when using a web container like Tomcat or Glassfish. I haven’t dug into this, but in those environments I would expect these approaches to return the root directory of your container, i.e., the root directory that something like Tomcat or Glassfish or the Play Framework is started in, but I could be wrong, that’s just a semi-educated guess.