How to get only the parent directory name of a specific file

How to get ddd on behalf of the path where test.java is located.

 File file = new File("C:/aaa/bbb/ccc/ddd/test.java"); 
+66
java java-io
Nov 19 '11 at 20:28
source share
5 answers

Use the File getParentFile() method and String.lastIndexOf() to get only the closest parent directory.

Marking a comment is better than lastIndexOf() :

 file.getParentFile().getName(); 

These solutions work only if the file has a parent file (for example, created using one of the file constructors with the parent File ). When getParentFile() is null, you need to use lastIndexOf or use something like Apache Commons' FileNameUtils.getFullPath() :

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

There are several options for saving / removing the prefix and trailing separator. You can use the same FilenameUtils class to grab a name from the result, use lastIndexOf , etc.

+96
Nov 19 2018-11-11T00:
source share

I do not think there is a magic method to get this straight. However, this should be good:

 File f = new File("C:/aaa/bbb/ccc/ddd/test.java"); String path = f.getParent(); System.out.println(path.substring(path.lastIndexOf("\\")+1,path.length())); 

f.getParent() may be null, so you should check it out.

EDIT: To make sure the result looks like this: C: / AAA / BBB / scc / ddd

+13
Nov 19 '11 at 20:47
source share

Use below

 File file = new File("file/path"); String parentPath = file.getAbsoluteFile().getParent(); 
+10
Jul 16 '14 at 8:35
source share

If you only have a String path and you do not want to create a 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)); } 
+4
Oct. 13 '14 at 7:34
source share
 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 add the "ddd" folder in another way;

 String currentFolder= "/" + currentPath.getName().toString(); 
+2
Sep 15 '15 at 23:14
source share



All Articles