Test.Javaが存在するパス名からddd
を取得する方法。
File file = new File("C:/aaa/bbb/ccc/ddd/test.Java");
File
のgetParentFile()
メソッド および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
などを使用できます。
File f = new File("C:/aaa/bbb/ccc/ddd/test.Java");
System.out.println(f.getParentFile().getName())
f.getParentFile()
はnullになる可能性があるため、確認する必要があります。
以下を使用して、
File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();
Java 7には、新しいPaths apiがあります。最新かつクリーンなソリューションは次のとおりです。
Paths.get("C:/aaa/bbb/ccc/ddd/test.Java").getParent().getFileName();
結果は次のようになります。
C:/aaa/bbb/ccc/ddd
文字列パスのみがあり、新しい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));
}
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();
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
)の前のエントリを指します
//get the parentfolder name
File file = new File( System.getProperty("user.dir") + "/.");
String parentPath = file.getParentFile().getName();
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);
}