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

10

139

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

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
Monoplegia answered 19/11, 2011 at 20:28 Comment(1)
Is this for a generic file, or are you trying to get the parent directory of your source file? If the latter, I'm not sure you understand Java compilation. At runtime, test.java probably won't even exist on the computer where the program is being run. It's the compiled .class file that is run. So this will only work if you know where ddd is located, in which case there is no point in finding it programatically; just hard code it.Monotint
L
173

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.

Lowgrade answered 19/11, 2011 at 20:39 Comment(4)
You don't need lastIndexOf, just use file.getParentFile().getName().Monotint
Just in case. If it returns null (if you created File instance with relative path) - try file.getAbsoluteFile().getParentFile().getName().Application
@MarkPeters That only works when the file was created with a parent File, though, which I'm guessing is relatively rarely.Lowgrade
stackoverflow.com/users/915663/nidu its works, thanksTuner
T
36

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().toString();

Result would be:

C:/aaa/bbb/ccc/ddd
Tijuana answered 27/2, 2018 at 23:9 Comment(1)
after getParent(), you need toString(), getFileName returns a relative Path object, representing "test.java" only.Bybee
D
20
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.

Dejadeject answered 19/11, 2011 at 20:47 Comment(1)
Just to make sure, the output is as follows: C:/aaa/bbb/ccc/dddGerri
C
20

Use below,

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();
Cacilie answered 16/7, 2014 at 8:35 Comment(1)
Worth pointing out that this method should have a parent set, even if the underlying file did not.Intromit
W
7

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));
}
Win answered 13/10, 2014 at 7:34 Comment(1)
This throws ArrayOutOfBoundsException if you are already on root location -"/"-Rms
F
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"

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

String currentFolder= "/" + currentPath.getName().toString();
Forecastle answered 15/9, 2015 at 23:14 Comment(0)
S
2

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);
}
Sarchet answered 15/2, 2018 at 15:7 Comment(0)
R
1

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

Riata answered 12/4, 2018 at 11:1 Comment(1)
It may surprise you, but there are still a lot of OS with different path separator characters.Sunstone
L
1

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
    }
}
Lennalennard answered 21/8, 2020 at 11:23 Comment(1)
parentFile.name is what i was looking forMoujik
N
0
    //get the parentfolder name
    File file = new File( System.getProperty("user.dir") + "/.");
    String parentPath = file.getParentFile().getName();
Nomography answered 20/3, 2019 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.