Java File getCanonicalFile()方法

java.io.File.getCanonicalFile() 方法返回此抽象路径名的规范形式。

1 语法

public File getCanonicalFile()

2 参数

3 返回值

该方法返回同一个文件或目录的规范路径名字符串表示。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.File.getCanonicalFile() 方法的例子
 */
import java.io.File;

public class Demo {
    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

热门文章

优秀文章