... since it seems that both returns the same string - take a look at this Scala code:
scala> val f = new File("log.txt")
scala> f.getPath
// res6: String = log
scala> f.toString
// res7: String = log
The toString()
method is defined on all Java classes. It is meant for debugging purposes and, unless explicitly defined by the user, cannot be relied on for anything other than displaying to the user.
In practice, the output doesn't really change between versions and, in many cases, you can be reasonably confident that it's going to be what you want, but, in principle, you should avoid any use of toString()
other than printing stuff to the user.
And that's why getPath()
exists. This method has a really well defined output value, which is also guaranteed to be accepted by methods that take a String
representing a path.
So, if you are going to use that path internally, use getPath()
. If you are going to print it as a debugging aid, use toString()
.
The toString() method for java.io.File class is overwritten to just call getPath(), so they will return the same result.
It will be very clear once you read the source here: toString()
The difference lies in which circumstance should you use one or the other.
The getPath
method will always return the String representation for path to the file. So if that's what you want(to pass the file path to another method etc..), you should call that method.
But if you want to convert the file to a textual presentation (maybe for logging) use the toString
method(see this question as well). The reason I say this is because if you use the toString
method where you should have used the getPath
method, and if the toString
implementation changes(maybe to show the file size as well) then your code will break.
If you look at java.io.file toString function actually calls path's getter.
public String toString() {
return getPath();
}