Fileクラス
getParentメソッド
一階層上のパスを表す文字列を返します。
getParent()
目次
1.getParentメソッド
インスタンス引数に与えられた文字列から、一階層上のパスを表す文字列を返します。
public String getParent()
これも単なる文字列操作だ。
実際にそのようなファイルやフォルダが
あっても無くても関係ない。
こんなのばっかね。
2.サンプルコード
いろいろやってみた。
ルートは Windowsの例だが、
区切り文字は「/」にしている。
//Sample03_01.java
import java.io.File;
class Sample03_01{
public static void main(String[] args){
File file01 = new File("c:/Users/hoge/ws/pathname.txt");
File file02 = new File("ws/pathname.txt");
File file03 = new File("pathname.txt");
File file04 = new File("c:/Users");
File file05 = new File("c:");
System.out.println("file01:\t" + file01.getParent());
System.out.println("file02:\t" + file02.getParent());
System.out.println("file03:\t" + file03.getParent());
System.out.println("file04:\t" + file04.getParent());
System.out.println("file05:\t" + file05.getParent());
}
}
コマンドライン
>cd ws
ws>javac Sample03_01.java
ws>java Sample03_01
file01: c:¥Users¥hoge¥ws
file02: ws
file03: null
file04: c:¥
file05: null
変数 file03
抽象パス名 "pathname.txt" に、親のディレクトリを表す部分が無いので、null になりました。
変数 file05
抽象パス名 "c:" は、ルート(ファイルシステムの最上位)であるために、null になりました。
示せない場合はnull
というのは使いやすいな。
お疲れ様でした。