简体   繁体   English

如何仅获取特定文件的父目录名称

[英]How to get just the parent directory name of a specific file

如何从 test.java 所在的路径名中获取ddd

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

Use File 's getParentFile() method and String.lastIndexOf() to retrieve just the immediate parent directory.使用FilegetParentFile()方法String.lastIndexOf()检索直接父目录。

Mark's comment is a better solution than lastIndexOf() : Mark 的评论是比lastIndexOf()更好的解决方案:

file.getParentFile().getName();

These solutions only works if the file has a parent file (eg, created via one of the file constructors taking a parent File ).这些解决方案仅在文件具有父文件时才有效(例如,通过采用父File的文件构造函数之一创建)。 When getParentFile() is null you'll need to resort to using lastIndexOf , or use something like Apache Commons' FileNameUtils.getFullPath() :getParentFile()为 null 时,您需要使用lastIndexOf ,或使用类似Apache Commons 的FileNameUtils.getFullPath()

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

There are several variants to retain/drop the prefix and trailing separator.有几种变体可以保留/删除前缀和尾随分隔符。 You can either use the same FilenameUtils class to grab the name from the result, use lastIndexOf , etc.您可以使用相同的FilenameUtils类从结果中获取名称,使用lastIndexOf等。

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

f.getParentFile() can be null, so you should check it. f.getParentFile()可以为空,所以你应该检查它。

Since Java 7 you have the new Paths api .从 Java 7 开始,您有了新的Paths api The modern and cleanest solution is:现代和最干净的解决方案是:

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

Result would be:结果将是:

C:/aaa/bbb/ccc/ddd

Use below,下面使用,

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

If you have just String path and don't want to create new File object you can use something like:如果您只有 String 路径并且不想创建新的 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"

if you need to append folder "ddd" by another path use;如果您需要通过另一个路径使用附加文件夹“ddd”;

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

From java 7 I would prefer to use Path.从 java 7 开始,我更喜欢使用 Path。 You only need to put path into:您只需要将路径放入:

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

and create some get method:并创建一些获取方法:

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

In Groovy:在 Groovy 中:

There is no need to create a File instance to parse the string in groovy.不需要创建File实例来解析 groovy 中的字符串。 It can be done as follows:可以按如下方式完成:

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

The split will create the array [C:, aaa, bbb, ccc, ddd, test.java] and index -2 will point to entry before the last one, which in this case is 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();

For 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM