10

How do we actually discard last file from java string and just get the file path directory?

Random Path input by user:

C:/my folder/tree/apple.exe

Desired output:

C:/my folder/tree/

closest solution i found is from here . The answer from this forum only display last string acquired not the rest of it. I want to display the rest of the string.

Community
  • 1
  • 1
kkk
  • 447
  • 1
  • 5
  • 12

2 Answers2

36

The easiest and most failsafe (read: cross-platform) solution is to create a File object from the path.

Like this:

File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();
mvreijn
  • 2,807
  • 28
  • 40
  • 4
    or use getParentFile() instead of getParent() to end up with a File object instead of a string. – nicomp Jul 11 '19 at 13:01
  • Check similar question https://stackoverflow.com/questions/28594297/get-the-directory-from-a-file-path-in-java-android – RenatoIvancic Jun 17 '22 at 06:50
4

Try that:

String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47