Java.io.File.getCanonicalFile() 方法
描述
java.io.File.getCanonicalFile() 方法返回此抽象路径名的规范形式。
声明
以下是 java.io.File.getCanonicalFile() 方法的声明 −
public File getCanonicalFile()
参数
NA
返回值
该方法返回由规范路径名字符串表示的相同文件或目录。
异常
IOException − 如果发生 I/O 错误
SecurityException − 如果无法访问系统属性值。
示例
下面的例子展示了 java.io.File.getCanonicalFile() 方法的使用。
package com.tutorialspoint;
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
File f = null;
File f1 = null;
String path = "";
boolean bool = false;
try {
// create new files
f = new File("C:\\Program Files\\..\\test.txt");
// create new canonical form file object
f1 = f.getCanonicalFile();
// returns true if the file exists
bool = f1.exists();
// returns absolute pathname
path = f1.getAbsolutePath();
// if file exists
if(bool) {
// prints
System.out.print(path+" Exists? "+ bool);
}
} catch(Exception e) {
// if any error occurs
e.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
C:\test.txt Exists? true

