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.
-
2I'm voting to close this question as off-topic because this is asking us for code without trying it ownself.Sougata Bose– Sougata Bose2015-04-15 12:33:51 +00:00Commented Apr 15, 2015 at 12:33
-
possible duplicate of Getting the directory name in javaanon– anon2015-04-15 12:44:47 +00:00Commented Apr 15, 2015 at 12:44
3 Answers
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()
Comments
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.