Java File getCanonicalFile()方法及示例

Java File getCanonicalFile()方法及示例

getCanonicalFile() 方法是File类的一部分。这个函数返回给定文件对象的经典文件。如果文件对象的文件路径是经典的,那么它就简单地返回当前文件对象的文件。 经典文件总是绝对的和唯一的,如果存在的话,该函数会从文件的路径中删除’.”.’。

例如: 如果我们使用 “program.txt “的路径创建一个文件对象,它将指向保存可执行程序的同一目录下的文件(如果你使用的是IDE,它将指向你保存该程序的文件)。这里,上述文件的路径是 “program.txt”,但这个路径不是绝对的(即不完整)。函数getCanonicalFile()将返回一个文件,其路径将是一个来自根目录的绝对和唯一的路径。一个现有文件的经典形式可能与同一不存在的文件的经典形式不同,一个现有文件的经典形式可能与同一文件被删除时的经典形式不同。

函数签名

public File getCanonicalFile()

函数语法

file.getCanonicalFile()

参数: 该函数不接受任何参数。

返回值: 该函数返回File对象,即给定File对象的Canonical File。

异常 该方法抛出以下异常

  • 安全异常: 如果所需的属性值不能被访问。
  • I/O异常: 如果发生I/O异常。

下面的程序将说明getCanonicalFile()方法的使用。

例1: 这里 “program.txt “是目前工作目录下的一个文件。

// Java program to demonstrate the
// use of getCanonicalFile() 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("program.txt");
  
            // Get the Canonical file
            // of the given file f
            File canonical = f.getCanonicalFile();
  
            // 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.getPath());
        }
        catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

输出

Original file path: program.txt
Canonical file path: C:\Users\pc\eclipse-workspace1\arnab\program.txt

Java中的文件getCanonicalFile方法及示例

例2: 我们得到了一个文件对象,我们必须从该文件对象中创建规范的文件。

// Java program to demonstrate the
// use of getCanonicalFile() 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 file
            // of the given file f
            File canonical = f.getCanonicalFile();
  
            // 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.getPath());
        }
        catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

输出

Original file path: c:\users\..\program
Canonical file path: C:\program

Java中的文件getCanonicalFile方法及示例

这些程序可能无法在在线IDE中运行。请使用离线IDE,并设置文件的路径

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程