138

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

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
yamenk
  • 46,736
  • 10
  • 93
  • 87
minil
  • 6,895
  • 16
  • 48
  • 55
  • 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. – Mark Peters Nov 19 '11 at 20:39

10 Answers10

170

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
35

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
phancuongviet
  • 311
  • 2
  • 11
neves
  • 33,186
  • 27
  • 159
  • 192
  • 2
    after getParent(), you need toString(), getFileName returns a relative Path object, representing "test.java" only. – zakmck Jun 20 '22 at 11:05
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.

Surasin Tancharoen
  • 5,520
  • 4
  • 32
  • 40
18

Use below,

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();
Ishan Liyanage
  • 2,237
  • 1
  • 26
  • 25
  • Worth pointing out that this method should have a parent set, even if the underlying file did not. – Pace Dec 23 '15 at 18:14
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));
}
Fedir Tsapana
  • 1,283
  • 16
  • 19
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();
gooamoko
  • 658
  • 12
  • 32
Crni03
  • 61
  • 6
1

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);
}
Peter S.
  • 470
  • 1
  • 7
  • 17
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

yamenk
  • 46,736
  • 10
  • 93
  • 87
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
    }
}
Yogesh Nikam Patil
  • 1,192
  • 13
  • 18
0
    //get the parentfolder name
    File file = new File( System.getProperty("user.dir") + "/.");
    String parentPath = file.getParentFile().getName();