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

138

如何从包含test.java的路径名中获取ddd

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

1
这是针对通用文件,还是您试图获取源文件的父目录?如果是后者,我不确定您是否理解Java编译。在运行时,“test.java”可能甚至不存在于运行程序的计算机上。运行的是已编译的“.class”文件。因此,只有在您知道“ddd”位于何处的情况下,才能使其正常工作,在这种情况下,通过编程查找它没有意义;只需硬编码即可。 - Mark Peters
10个回答

170

16
不需要使用lastIndexOf,只需使用file.getParentFile().getName() - Mark Peters
16
以防万一。如果返回 null(如果你用相对路径创建了 File 实例)- 尝试使用 file.getAbsoluteFile().getParentFile().getName() - nidu
1
@MarkPeters,这仅适用于使用父文件创建的文件,我猜这种情况相对较少。 - Dave Newton
https://stackoverflow.com/users/915663/nidu 它有效了,谢谢。 - Mang Jojot

35

自从Java 7之后,你可以使用新的Paths API。现代和最简洁的解决方案是:

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

结果将是:

C:/aaa/bbb/ccc/ddd

2
在调用getParent()方法之后,您需要使用toString()方法。getFileName()方法返回一个相对路径对象,仅表示"test.java"。 - zakmck

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

应该检查f.getParentFile()是否为null。


1
只是为了确认,输出如下:C:/aaa/bbb/ccc/ddd - Guy Avraham

18

请使用以下内容:

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

值得指出的是,即使底层文件没有父级设置,这种方法也应该有一个父级设置。 - Pace

7

如果您只有路径字符串而不想创建新的文件对象,可以使用类似以下的方法:

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
如果您已经在根目录"/"上,这将抛出ArrayIndexOutOfBoundsException错误。 - Jnmgr

3
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();

1

在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

你可能会感到惊讶,但仍然有很多具有不同路径分隔符字符的操作系统。 - Cavaler

1

从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);
}

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

parentFile.name是我正在寻找的。 - Guilherme Campos Hazan
parentFile.name是我正在寻找的内容 - undefined

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接