web-dev-qa-db-ja.com

特定のファイルの親ディレクトリ名だけを取得する方法

Test.Javaが存在するパス名からdddを取得する方法。

File file = new File("C:/aaa/bbb/ccc/ddd/test.Java");
95
minil

FilegetParentFile()メソッド およびString.lastIndexOf()を使用して、直接の親ディレクトリを取得justします。

マークのコメントは、lastIndexOf()よりも優れたソリューションです。

file.getParentFile().getName();

これらのソリューションは、ファイルに親ファイルがある場合にのみ機能します(たとえば、親Fileを使用するファイルコンストラクターの1つを介して作成されます)。 getParentFile()がnullの場合、lastIndexOfを使用するか、または Apache Commons 'FileNameUtils.getFullPath() のようなものを使用する必要があります。

FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd

プレフィックスと末尾のセパレータを保持/削除するためのいくつかのバリアントがあります。同じFilenameUtilsクラスを使用して、結果から名前を取得するか、lastIndexOfなどを使用できます。

126
Dave Newton
File f = new File("C:/aaa/bbb/ccc/ddd/test.Java");
System.out.println(f.getParentFile().getName())

f.getParentFile()はnullになる可能性があるため、確認する必要があります。

18

以下を使用して、

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();
14
Ishan Liyanage

Java 7には、新しいPaths apiがあります。最新かつクリーンなソリューションは次のとおりです。

Paths.get("C:/aaa/bbb/ccc/ddd/test.Java").getParent().getFileName();

結果は次のようになります。

C:/aaa/bbb/ccc/ddd
8
neves

文字列パスのみがあり、新しいFileオブジェクトを作成したくない場合は、次のようなものを使用できます。

public static String getParentDirPath(String fileOrDirPath) {
    boolean endsWithSlash = fileOrDirPath.endsWith(File.separator);
    return fileOrDirPath.substring(0, fileOrDirPath.lastIndexOf(File.separatorChar, 
            endsWithSlash ? fileOrDirPath.length() - 2 : fileOrDirPath.length() - 1));
}
4
Fedir Tsapana
File file = new File("C:/aaa/bbb/ccc/ddd/test.Java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"

別のパスを使用してフォルダ「ddd」を追加する必要がある場合。

String currentFolder= "/" + currentPath.getName().toString();
2
Crni03

In Groovy:

Groovyで文字列を解析するためにFileインスタンスを作成する必要はありません。次のように実行できます。

String path = "C:/aaa/bbb/ccc/ddd/test.Java"
path.split('/')[-2]  // this will return ddd

分割は配列[C:, aaa, bbb, ccc, ddd, test.Java]を作成し、インデックス-2は最後のエントリ(この場合はddd)の前のエントリを指します

0
yamenk
    //get the parentfolder name
    File file = new File( System.getProperty("user.dir") + "/.");
    String parentPath = file.getParentFile().getName();
0
Oscar Betgen

Java 7からは、Pathを使用したいと思います。あなただけにパスを入れる必要があります:

Path dddDirectoryPath = Paths.get("C:/aaa/bbb/ccc/ddd/test.Java");

getメソッドを作成します。

public String getLastDirectoryName(Path directoryPath) {
   int nameCount = directoryPath.getNameCount();
   return directoryPath.getName(nameCount - 1);
}
0
Peter S.