java.io.File类提供了以下获取文件路径的方法。

  • getPath() - 此方法返回表示用于创建关联File对象的路径的字符串。
  • getAbsolutePath() - 如果路径字符串是相对的,则在解析当前目录后返回路径字符串,从而产生一个完全限定的路径。
  • getCanonicalPath() - 此方法在解析当前目录的任何相对路径后返回路径字符串,并删除任何相对路径元素,例如 (...)。

下面是一个Java获取文件的路径的例子。

文件:FilePathExample.java -

package com.yiibai.tutorial.io;

import java.io.File;
import java.io.IOException;

/**
 * @author yiibai
 * FilePathExample.java
 * Nov 5, 2016
 */
public class FilePathExample {
    public static void main(String[] args) throws IOException {
        File file=new File("../../file.txt");
        System.out.println();

        if(file.exists()){
            /*Get path*/
            String path=file.getPath();
            System.out.println("Path is : "+path);

            /*Get absolute path*/
            String absolutePath=file.getAbsolutePath();
            System.out.println("Absolute path is : "+absolutePath);

            /*Get canonical path*/
            String canonicalPath=file.getCanonicalPath();
            System.out.println("Canonical path is : "+canonicalPath);
        }else{
            System.out.println("File does not exist");
        }
    }
}

执行上面示例代码,得到以下结果:

Path is : ..\..\file.txt
Absolute path is : D:\Work\Workspace\yiibai.tutorial\..\..\file.txt
Canonical path is : D:\Work\file.txt