AndroidのJavaでファイルパス情報から一つ上の階層のパスを取得するには、File クラスの getParent() メソッドを使用するのが簡単で、確実に動作します。
以下に具体的な例を示します
public class ParentPathExample {
public static void main(String[] args) {
// 現在のファイルパス情報(例として指定)
String currentPath = “/storage/emulated/0/Android/data/com.example.app/files/ sample.txt”;
// Fileオブジェクトを作成
File file = new File(currentPath);
// 一つ上の階層のパスを取得
String parentPath = file.getParent();
// 結果を表示
if (parentPath != null) {
System.out.println("一つ上の階層のパス: " + parentPath);
} else {
System.out.println("親ディレクトリが存在しません。");
}
}
}
コードの説明
Fileクラスを使用:Fileクラスを使うと、指定したパスのファイルやディレクトリにアクセスできます。
getParent()メソッド:- このメソッドは、現在のパスの親ディレクトリのパスを文字列として返します。
- 例えば、
/storage/emulated/0/Android/data/com.example.app/files/sample.txtから/storage/emulated/0/Android/data/com.example.app/filesを取得します。
nullチェック:- ファイルがルートディレクトリにある場合や、親ディレクトリが存在しない場合は
getParent()がnullを返すので、必ずチェックします。
- ファイルがルートディレクトリにある場合や、親ディレクトリが存在しない場合は



コメント