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

JavaGroovyJava Io

Java Problem Overview


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

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

Java Solutions


Solution 1 - Java

Use File's getParentFile() method and String.lastIndexOf() to retrieve just the immediate parent directory.

Mark's comment is a better solution thanlastIndexOf():

file.getParentFile().getName();

These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File). When getParentFile() is null you'll need to resort to using lastIndexOf, or use something like 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.

Solution 2 - Java

Since Java 7 you have the new 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

Solution 3 - Java

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.

Solution 4 - Java

Use below,

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

Solution 5 - Java

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

Solution 6 - Java

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;

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

Solution 7 - Java

From java 7 I would prefer to use 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);
}

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionminilView Question on Stackoverflow
Solution 1 - JavaDave NewtonView Answer on Stackoverflow
Solution 2 - JavanevesView Answer on Stackoverflow
Solution 3 - JavaSurasin TancharoenView Answer on Stackoverflow
Solution 4 - JavaIshan LiyanageView Answer on Stackoverflow
Solution 5 - JavaFedir TsapanaView Answer on Stackoverflow
Solution 6 - JavaCrni03View Answer on Stackoverflow
Solution 7 - JavaPeter S.View Answer on Stackoverflow
Solution 8 - JavayamenkView Answer on Stackoverflow
Solution 9 - JavaOscar BetgenView Answer on Stackoverflow
Solution 10 - JavaYogesh Nikam PatilView Answer on Stackoverflow