How to get just the parent directory name of a spe

2019-01-04 01:44发布

How to get ddd from the path name where the test.java resides.

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

8条回答
【Aperson】
2楼-- · 2019-01-04 01:47

If you have just String path and don't want to create new File object you can use something like:

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));
}
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-04 01:50
File f = new File("C:/aaa/bbb/ccc/ffffd/test.java");
System.out.println(f.getParentFile().getName())

f.getParentFile() can be null, so you should check it.

查看更多
何必那么认真
4楼-- · 2019-01-04 01:53
File file = new File("C:/aaa/bbb/ccc/ffffd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ffffd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ffffd"

if you need to append folder "ffffd" by another path use;

String currentFolder= "/" + currentPath.getName().toString();
查看更多
你好瞎i
5楼-- · 2019-01-04 02:01

From java 7 I would prefer to use Path. You only need to put path into:

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

and create some get method:

public String getLastDirectoryName(Path directoryPath) {
   int nameCount = directoryPath.getNameCount();
   return directoryPath.getName(nameCount - 1);
}
查看更多
时光不老,我们不散
6楼-- · 2019-01-04 02:04

In Groovy:

There is no need to create a File instance to parse the string in groovy. It can be done as follows:

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

The split will create the array [C:, aaa, bbb, ccc, ffffd, test.java] and index -2 will point to entry before the last one, which in this case is ffffd

查看更多
SAY GOODBYE
7楼-- · 2019-01-04 02:05

In Java 7 you have the new Paths api. The modern and cleanest solution is:

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

Result would be:

C:/aaa/bbb/ccc/ffffd
查看更多
登录 后发表回答