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.

2 Answers 2

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

or use getParentFile() instead of getParent() to end up with a File object instead of a string.
4

Try that:

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

3 Comments

you shall take into account that separator is nit garanted to be forward slash
Much better in my opinion - not making a file. Especially if the said file does not actually exist (yet). Worked perfectly for my needs.
You are not "making a file" by creating a File object. It's just the container for java.io functions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.