[Java]相対指定したファイル名からそのファイルのあるディレクトリの絶対パスを取り出したい。
標準のメソッドではできないのか。。File#getParent()はnullになる。
環境
iotest.java
import java.io.*;
public class iotest {
public static void main(String... args){
File f = new File(args[0]);
try {
System.out.println( args[0]+" exists: "+f.exists());
System.out.println("getPath(): "+f.getPath());
System.out.println("AbsolutePath(): "+f.getAbsolutePath());
System.out.println("CanonicalPath(): "+f.getCanonicalPath());
System.out.println("parent(): "+ f.getParent());
}catch (IOException e){}
}
}
コンパイル
D:\iote>javac iotest.java
iotest.classはD:\ioteに存在するファイル
dam.txtはD:\ioteに存在しないファイル
実行1
D:\iote>java iotest iotest.class
結果1
iotest.class exists: true
getPath(): iotest.class
AbsolutePath(): D:\iote\iotest.class
CanonicalPath(): D:\iote\iotest.class
parent(): null
実行2
D:\iote>java iotest D:\iote\iotest.class
結果2
D:\iote\iotest.class exists: true
getPath(): D:\iote\iotest.class
AbsolutePath(): D:\iote\iotest.class
CanonicalPath(): D:\iote\iotest.class
parent(): D:\iote
実行3
D:\iote>java iotest ..\iote\iotest.class
結果3
..\iote\iotest.class exists: true
getPath(): ..\iote\iotest.class
AbsolutePath(): D:\iote\..\iote\iotest.class
CanonicalPath(): D:\iote\iotest.class
parent(): ..\iote
実行4
D:\iote>java iotest dam.txt
結果4
dam.txt exists: false
getPath(): dam.txt
AbsolutePath(): D:\iote\dam.txt
CanonicalPath(): D:\iote\dam.txt
parent(): null
実行5
D:\iote>java iotest D:\iote\dam.txt
結果5
D:\iote\dam.txt exists: false
getPath(): D:\iote\dam.txt
AbsolutePath(): D:\iote\dam.txt
CanonicalPath(): D:\iote\dam.txt
parent(): D:\iote
実行6
D:\iote>java iotest ..\iote\dam.txt
結果6
..\iote\dam.txt exists: false
getPath(): ..\iote\dam.txt
AbsolutePath(): D:\iote\..\iote\dam.txt
CanonicalPath(): D:\iote\dam.txt
parent(): ..\iote
..\で指定したら必ずしもgetParent()はnullにはならない。
でも結局
File#getAbsoluteDirectoryPath()みたいなメソッドがないので
args[0]にhoge.txtを指定したばあいに、
File hoge = new File(args[0])からhoge.txtのおかれたディレクトリを絶対パスで
取り出すすべがない。。
で、どうしたか。
File infile = new File(args[0]);
String dirfullpath = new File(infile.getCanonicalPath()).getParent();
一行で書くなら
String dirfullpath = new File(new File(args[0]).getCanonicalPath()).getParent();
チェックは必要だけど、手っ取りばやくフルパスを仮定してファイルパスを取得するには
こうするしか思いつかなかった。
何か良い方法はありませんかね。
コメント
コメントを投稿
「コメントを投稿できるユーザー」の範囲は変更される可能性があります。