作成 2010.01.05
更新 2011.10.26
更新 2011.10.26
Java でファイル パスを取得する際に最適なメソッドの調査結果
検証環境
Ubuntu 9.10, sun-java6-jdk 6-15-1
Windows 7, java version "1.6.0_17"
検証コード
myfile.java
import java.io.File;
class myfile{
public static void main(String args[]){
if(args.length >= 1){
File f = new File(args[0]);
System.out.println(args[0]);
System.out.println(f.getPath());
System.out.println(f.toURI());
System.out.println(f.getParent());
System.out.println(f.getAbsolutePath());
try{
System.out.println(f.getCanonicalPath());
}catch(Exception e){
System.out.println("f.getCanonicalPath():" + e.getMessage());
}
}
}
}
実行結果
正式なパスは getCanonicalPath() で取得するのが最適。
- Ubuntu での実行結果
$ javac myfile.java $ java myfile /var/www/html/../../../etc/passwd /var/www/html/../../../etc/passwd /var/www/html/../../../etc/passwd file:/var/www/html/../../../etc/passwd /var/www/html/../../../etc /var/www/html/../../../etc/passwd /etc/passwd
- Windows での実行結果
> javac myfile.java > java myfile "\wwwroot\html\..\..\windows" \wwwroot\html\..\..\windows \wwwroot\html\..\..\windows file:/C:/wwwroot/html/../../windows \wwwroot\html\..\.. C:\wwwroot\html\..\..\windows C:\windows
タグ: Java