如何从包含test.java的路径名中获取ddd
。
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
使用 File
的 getParentFile()
方法以及 String.lastIndexOf()
方法来获取仅包含直接父级目录的路径。
Mark 的评论是比 lastIndexOf()
更好的解决方案:
file.getParentFile().getName();
这些解决方案仅适用于文件具有父文件的情况(例如,通过使用一个带有父File
的文件构造函数创建)。当getParentFile()
为null时,您需要使用lastIndexOf
或类似于Apache Commons的FileNameUtils.getFullPath()
来解决问题:
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd
保留/删除前缀和尾部分隔符有几种变体。您可以使用相同的 FilenameUtils
类从结果中获取名称,也可以使用 lastIndexOf
等方法。
lastIndexOf
,只需使用file.getParentFile().getName()
。 - Mark Petersnull
(如果你用相对路径创建了 File
实例)- 尝试使用 file.getAbsoluteFile().getParentFile().getName()
。 - nidu自从Java 7之后,你可以使用新的Paths API。现代和最简洁的解决方案是:
Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().toString();
结果将是:
C:/aaa/bbb/ccc/ddd
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();
如果您只有路径字符串而不想创建新的文件对象,可以使用类似以下的方法:
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();
在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
。从Java 7开始,我更喜欢使用Path。您只需要将路径放入:
Path dddDirectoryPath = Paths.get("C:/aaa/bbb/ccc/ddd/test.java");
public String getLastDirectoryName(Path directoryPath) {
int nameCount = directoryPath.getNameCount();
return directoryPath.getName(nameCount - 1);
}
对于 Kotlin:
fun getFolderName() {
val uri: Uri
val cursor: Cursor?
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(MediaStore.Audio.AudioColumns.DATA)
cursor = requireActivity().contentResolver.query(uri, projection, null, null, null)
if (cursor != null) {
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
}
while (cursor!!.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data)
val fileName: String = File(absolutePathOfImage).parentFile.name
}
}
//get the parentfolder name
File file = new File( System.getProperty("user.dir") + "/.");
String parentPath = file.getParentFile().getName();