Java io 库:File.toString() 和 File.getPath() 有什么区别

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

... 因为看起来 returns 是同一个字符串 - 看看这个 Scala 代码:

scala> val f = new File("log.txt")
scala> f.getPath
// res6: String = log
scala> f.toString
// res7: String = log

它们是相同的。参见javadocs。直接引用自 link:

getPath()
    Converts this abstract pathname into a pathname string.

toString()
    Returns the pathname string of this abstract pathname. 
    This is just the string returned by the getPath() method.

java.io.File class 的 toString() 方法被覆盖为仅调用 getPath(),因此它们将 return 得到相同的结果。

在这里阅读源代码就会很清楚:toString()

toString() 方法定义在 all Java 类 上。它用于 调试 目的,除非用户明确定义,否则除了向用户显示外,不能依赖它做任何事情。

实际上,版本之间的输出并没有真正改变,在许多情况下,您可以有理由相信它会是您想要的,但是,原则上,你应该避免使用 toString() 除了打印给用户的东西。

这就是 getPath() 存在的原因。 这个方法有一个非常明确定义的输出值,也保证接受采用String表示路径的方法.

因此,如果您要在内部使用该路径,请使用 getPath()。如果您要打印它作为调试辅助工具,请使用 toString().

区别在于你应该在什么情况下使用其中一个。 getPath 方法将始终 return 文件路径的字符串表示形式。所以如果这就是你想要的(将文件路径传递给另一个方法等),你应该调用那个方法。

但是,如果您想将文件转换为文本表示(可能用于记录),请使用 toString 方法 (see this question as well)。我这样说的原因是,如果你在你应该使用 getPath 方法的地方使用 toString 方法,并且如果 toString 实现发生变化(也可能显示文件大小)那么你的代码就会崩溃。

如果你看 java.io.file toString 函数实际上调用路径的 getter。

public String toString() {
    return getPath();
}