0

Suppose my file path is "/path/to/file/foo.txt". i want to get "/path/to/file" . means i want to get the path to the folder only where my file exist.

2
  • 2
    I'm voting to close this question as off-topic because this is asking us for code without trying it ownself. Commented Apr 15, 2015 at 12:33
  • possible duplicate of Getting the directory name in java Commented Apr 15, 2015 at 12:44

3 Answers 3

4

This should work

File file = new File("/path/to/file/foo.txt");
System.out.println(file.getParent());

edit

Find the reated Java doc here: File.html#getParent()

Sign up to request clarification or add additional context in comments.

Comments

1

Refer the post: How to get just the parent directory name of a specific file

Use File's getParentFile() method and String.lastIndexOf() to retrieve just the immediate parent directory.

Mark's comment is a better solution thanlastIndexOf():

file.getParentFile().getName();

These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File). When getParentFile() is null you'll need to resort to using lastIndexOf, or use something like Apache Commons' FileNameUtils.getFullPath():

FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd

There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils class to grab the name from the result, use lastIndexOf, etc.

Comments

0

Something like this?

File file = new File("/path/to/file/foo.txt");
file.getAbsolutePath();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.