Get only the path directory and cancel the file in Java

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

Random user input path:

C:/my folder/tree/apple.exe 

Required Conclusion:

 C:/my folder/tree/ 

The closest solution I found is here . The answer from this forum shows only the last line received not by everyone else. I want to display the rest of the line.

+7
java file
source share
2 answers

The simplest and most reliable (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(); 
+21
source share

Try the following:

 String path = "C:/my folder/tree/apple.exe"; path = path.substring(0, path.lastIndexOf("/")+1); 
+1
source share

All Articles