Java中的getPath(),getAbsolutePath()和getCanonicalPath()有什么区别? [英] What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

查看:102
本文介绍了Java中的getPath(),getAbsolutePath()和getCanonicalPath()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getPath() getAbsolutePath() getCanonicalPath之间的区别是什么? )在Java中?

我什么时候使用每一个?

And when do I use each one?

推荐答案

考虑这些文件名:

C:\ temp\file.txt - 这是路径,绝对路径和规范路径。

C:\temp\file.txt - This is a path, an absolute path, and a canonical path.

.\file.txt - 这是一条路。它既不是绝对路径,也不是规范路径。

.\file.txt - This is a path. It's neither an absolute path nor a canonical path.

C:\ temp \ myapp \ bin \ .. \\ ..\file.txt - 这是路径和绝对路径。它不是规范路径。

C:\temp\myapp\bin\..\\..\file.txt - This is a path and an absolute path. It's not a canonical path.

规范路径始终是绝对路径。

A canonical path is always an absolute path.

从路径转换为规范路径使其成为绝对路径(通常在当前工作目录上添加,例如 ./ file.txt 变为 c:/temp/file.txt )。文件的规范路径只是净化路径,删除和解析诸如 .. \ 之类的东西并解析符号链接(在unixes上)。

Converting from a path to a canonical path makes it absolute (usually tack on the current working directory so e.g. ./file.txt becomes c:/temp/file.txt). The canonical path of a file just "purifies" the path, removing and resolving stuff like ..\ and resolving symlinks (on unixes).

另请注意以下nio.Paths示例:

Also note the following example with nio.Paths:

String canonical_path_string = "C:\\Windows\\System32\\";
String absolute_path_string = "C:\\Windows\\System32\\drivers\\..\\";

System.out.println(Paths.get(canonical_path_string).getParent());
System.out.println(Paths.get(absolute_path_string).getParent());

虽然两条路径都指向相同的位置,但输出将完全不同:

While both paths refer to the same location, the output will be quite different:

C:\Windows
C:\Windows\System32\drivers

这篇关于Java中的getPath(),getAbsolutePath()和getCanonicalPath()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆