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.

Sritam Jagadev
  • 955
  • 4
  • 18
  • 46
  • 2
    I'm voting to close this question as off-topic because this is asking us for code without trying it ownself. – Sougata Bose Apr 15 '15 at 12:33
  • possible duplicate of [Getting the directory name in java](http://stackoverflow.com/questions/3009981/getting-the-directory-name-in-java) – Nic Apr 15 '15 at 12:44

3 Answers3

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()

SubOptimal
  • 22,518
  • 3
  • 53
  • 69
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.

Community
  • 1
  • 1
0

Something like this?

File file = new File("/path/to/file/foo.txt");
file.getAbsolutePath();
khumche
  • 82
  • 5