Java File getCanonicalPath() 方法及例子
getCanonicalPath() 方法是Path类的一个组成部分。这个函数返回给定文件对象的Canonical路径名。如果文件对象的路径名是Canonical,那么它只是返回当前文件对象的路径。Canonical路径总是绝对的和唯一的,如果存在的话,该函数将删除路径中的’.’ ‘…’。
例如: 如果我们使用 “program.txt “的路径创建一个文件对象,它将指向保存可执行程序的同一目录下的文件(如果你使用的是IDE,它将指向你保存程序的文件)。这里,上述文件的路径是 “program.txt”,但这个路径不是绝对的(即不完整)。函数getCanonicalPath()将返回一个路径,这将是一个来自根目录的绝对和唯一路径。现有文件的规范形式可能与同一非现有文件的规范形式不同,现有文件的规范形式可能与删除同一文件的规范形式不同。
函数签名
public String getCanonicalPath()
函数语法
file.getCanonicalPath()
参数: 该函数不接受任何参数。
返回值: 如果给定文件对象的经典路径,该函数返回一个字符串值。
异常: 该方法抛出以下异常。
- 如果所需的属性值不能被访问,则出现 安全异常 。
- 如果发生I / O异常,则抛出I/O异常。
下面的程序将说明getAbsolutePath()方法的使用。
例1: 我们有一个指定路径的文件对象,我们将尝试找到它的典型路径。
// Java program to demonstrate the
// use of getCanonicalPath() function
import java.io.*;
public class solution {
public static void main(String args[])
{
// try-catch block to handle exceptions
try {
// Create a file object
File f = new File("c:\\program");
// Get the Canonical path of file f
String canonical = f.getCanonicalPath();
// Display the file path of the file object
// and also the file path of Canonical file
System.out.println("Original file path : "
+ f.getPath());
System.out.println("Canonical file path : "
+ canonical);
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
输出
Original file path : c:\program
Canonical file path : C:\program
例2: 我们有一个指定路径的文件对象,我们将尝试找到它的典型路径。
// Java program to demonstrate the
// use of getCanonicalPath() function
import java.io.*;
public class solution {
public static void main(String args[])
{
// try-catch block to handle exceptions
try {
// Create a file object
File f = new File("c:\\users\\..\\program");
// Get the Canonical path of file f
String canonical = f.getCanonicalPath();
// Display the file path of the file object
// and also the file path of Canonical file
System.out.println("Original file path : "
+ f.getPath());
System.out.println("Canonical file path : "
+ canonical);
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
输出
Original file path : c:\users\..\program
Canonical file path : C:\program
这些程序可能无法在在线IDE中运行。请使用离线IDE,并设置文件的路径