getName()
,getAbsoluteFile()
和getCanonicalFile()
getPath()
,getAbsolutePath()
和getCanonicalPath()
3 回答
Concise version:
File.getName()
returns the file name part as a string; i.e. the bit after the last file separator.File.getPath()
returns the complete pathname as a string.File.getAbsolutePath()
turns the complete pathname as a string, after mapping the path to an absolute path if it is currently relative. No attempt is made to validate the path.File.getAbsoluteFile()
does the same thing asFile.getAbsolutePath()
, except that the result is aFile
.File.getCanonicalPath()
maps the path to an absolute path (if it is currently relative) and then attempts to canonicalize it. This process is OS dependent, but it typically involves following symbolic links and replacing ".", ".." and empty names with their canonical equivalents. The result is the canonicalized path string.File.getCanonicalFile()
does the same asFile.getCanonicalPath()
except that its result is aFile
.
The first 4 are really just text-based manipulations of the original File
object. They make no attempt to check that any part of the path corresponds to anything in the file system.
The last 2 involve checking the path to the last-named component of the File
. If the path involves non-existent directories, broken links, directories than cannot be read and so on, you are liable to get an IOException.
For more details, follow to the respective methods' javadoc links.
NOTE in 2020 - If you still are cutting new code that uses the File
API, you should seriously consider using the java.nio.file
APIs instead:
- a
Path
object most directly corresponds to aFile
object - the
Files
andPaths
classes provide numerous static methods that operate onPath
objects,
The advantages of the newer APIs include:
- Many operations now throw an exception to tell you why they failed.
- There is support for a variety of file system semantics; e.g. different kinds of access control, file attributes and so on.
- There is support for directory watchers, file tree traversal, and so on.
- There is support for virtual file systems implemented within the JVM.
- Some of the odd behaviors of
File
on Windows (which could not be fixed inFile
for compatibility reasons) have been addressed.
Java API 具有 File 对象的完整描述以及它包含的所有方法。
获取名称():http : //docs.oracle.com/javase/7/docs/api/java/io/File.html#getName()
getCanoniacalPath(): http ://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalPath( )
getAbsolutePath(): http ://docs.oracle.com/javase/7/docs/api/java/io/File.html#getAbsolutePath ()
getAbsoluteFile(): http ://docs.oracle.com/javase/7/docs/api/java/io/File.html#getAbsoluteFile ()
getCanonicalFile(): http ://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalFile( )
此页面清楚地解释了所有这六种方法之间的差异:http ://www.avajava.com/tutorials/lessons/whats-the-difference-between-a-files-path-absolute-path-and-规范路径.html