8

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
  • 427
  • 1
  • 5
  • 11

2 Answers2

33

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,652
  • 25
  • 40
  • 3
    or use getParentFile() instead of getParent() to end up with a File object instead of a string. – nicomp Jul 11 '19 at 13:01
4

Try that:

String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);
Florent Bayle
  • 10,752
  • 4
  • 33
  • 44