Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java io library: What is the difference between File.toString() and File.getPath()

Tags:

java

jvm

scala

... 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
like image 868
lolski Avatar asked Feb 05 '26 20:02

lolski


1 Answers

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().

like image 195
Daniel C. Sobral Avatar answered Feb 07 '26 09:02

Daniel C. Sobral