FileクラスのgetXxxで取得できる文字列

Javaでファイルオブジェクトを使用してファイルを読み込んだりする際、そもそもFileオブジェクトの次のメソッドではどのような文字列が取得できるのか、試した結果を張っておきます。

使用したプログラム

package test;

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

public class TestFileString {

    /**
     * メインメソッド。
     *
     * @param args コマンドライン引数
     */
    public static void main(final String[] args) {

        System.out.println("main start");
        TestFileString main = new TestFileString();
        for (String s : args) {
            System.out.println(String.format("ファイル「%s」で実行", s));
            main.execute(s);
        }
        System.out.println("main end");
    }

    /**
     * 主処理。
     *
     * @param fileName ファイル
     */
    public final void execute(final String fileName) {

        File readFile = null;
        try {
            readFile = new File(fileName);

            System.out.println("readFile.getAbsolutePath()");
            System.out.println(readFile.getAbsolutePath() + "\n");
            System.out.println("readFile.getCanonicalPath()");
            System.out.println(readFile.getCanonicalPath() + "\n");
            System.out.println("readFile.getName()");
            System.out.println(readFile.getName() + "\n");
            System.out.println("readFile.getParent()");
            System.out.println(readFile.getParent() + "\n");
            System.out.println("readFile.getPath()");
            System.out.println(readFile.getPath() + "\n");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

実行結果1(ファイルの場合)

main start
ファイル「..\practice\pom.xml」で実行
readFile.getAbsolutePath()
C:\Documents and Settings\hoge\workspace\practice\..\practice\pom.xml

readFile.getCanonicalPath()
C:\Documents and Settings\hoge\workspace\practice\pom.xml

readFile.getName()
pom.xml

readFile.getParent()
..\practice

readFile.getPath()
..\practice\pom.xml

main end

getAbsolutePath()は、Fileコンストラクタに与えられたとおりのパスを踏まえてフルパスを返すのに対し、getCanonicalPath()では、重複した表現を回避し、本当のフルパスを返しているのが特徴だろうか。

また、getPath()では与えられたパスをそのまま返しているように見える。
getName()は、ファイル名だけが取得でき、getPath()では与えられたパスからファイル名と末尾のパスセパレータ(File.pathSeparator)を除いた文字列が取得される。

実行結果2(ディレクトリの場合)

main start
ファイル「..\practice」で実行
readFile.getAbsolutePath()
C:\Documents and Settings\hoge\workspace\practice\..\practice

readFile.getCanonicalPath()
C:\Documents and Settings\hoge\workspace\practice

readFile.getName()
practice

readFile.getParent()
..

readFile.getPath()
..\practice

main end

getAbsolutePath()、getCanonicalPath()、及びgetPath()についてはファイルと同じようである。

getName()は、ディレクトリ名だけが取得でき、getPath()では与えられたパスからディレクトリ名と末尾のパスセパレータ(File.pathSeparator)を除いた文字列が取得される。