Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path directory only and discard file in Java

Tags:

java

file

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.

like image 413
kkk Avatar asked Mar 03 '14 07:03

kkk


2 Answers

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();
like image 107
mvreijn Avatar answered Sep 18 '22 00:09

mvreijn


Try that:

String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);
like image 35
Florent Bayle Avatar answered Sep 20 '22 00:09

Florent Bayle