【Java】 Path の扱い あれこれ

■ カレントディレクトリの取得

new File(".").getAbsoluteFile().getParent()
or
System.getProperty("user.dir")
を使う

サンプル

System.out.println(new File(".").getAbsolutePath());
System.out.println(new File(".").getAbsoluteFile().getParent());
System.out.println(System.getProperty("user.dir"));

出力結果

C:\pg\eclipse\workspace\HelloWorld\.
C:\pg\eclipse\workspace\HelloWorld
C:\pg\eclipse\workspace\HelloWorld

参考文献

http://www.geocities.co.jp/AnimeComic-Ink/2723/tips/java/4.html
http://isann.blog2.fc2.com/blog-entry-21.html

■ ユーザホームディレクトリの取得

System.getProperty("user.home")
を使う

■ パスの結合

String filePath = new File(【ディレクトリ1】, 【ディレクトリ2】).getPath();
or
Path path = Paths.get(【ディレクトリ1】, 【ディレクトリ2】)

サンプル

String currentPath1 = new File(".").getAbsolutePath();
System.out.println(new File(currentPath1, "test/test.txt").getPath());
System.out.println(new File(currentPath1, "/test/test.txt").getPath());
String currentPath2 = System.getProperty("user.dir");
System.out.println(new File(currentPath2, "test/test.txt").getPath());
System.out.println(new File(currentPath2, "/test/test.txt").getPath());

System.out.println();

Path path1 = FileSystems.getDefault().getPath("/test/test.txt");
System.out.println(path1.toString());
System.out.println(path1.toAbsolutePath());
Path path2 = Paths.get(System.getProperty("user.dir"), "test", "test.txt");
System.out.println(path2.toString());
System.out.println(path2.toAbsolutePath());		

出力結果

C:\pg\eclipse\workspace\HelloWorld\.\test\test.txt
C:\pg\eclipse\workspace\HelloWorld\.\test\test.txt
C:\pg\eclipse\workspace\HelloWorld\test\test.txt
C:\pg\eclipse\workspace\HelloWorld\test\test.txt

\test\test.txt
C:\test\test.txt
C:\pg\eclipse\workspace\HelloWorld\test\test.txt
C:\pg\eclipse\workspace\HelloWorld\test\test.txt

参考文献

http://d.hatena.ne.jp/tilfin/20070502/1178288324
http://docs.oracle.com/cd/E26537_01/tutorial/essential/io/pathOps.html