Consider the code:
File file = new File("c:\\temp\\java\\testfile");
testfile is a file, and it may or may not exist.
I want to get the directory c:\\temp\\java\\ using the File object. How do I go about doing this?
Consider the code:
File file = new File("c:\\temp\\java\\testfile");
testfile is a file, and it may or may not exist.
I want to get the directory c:\\temp\\java\\ using the File object. How do I go about doing this?
6/10/2021 All current answers fail if eg. the given file is...
new File("." + File.separator + "."); //Odd, yes, but I've seen similar more often than you'd think is possible
For a simple, robust solution, try...
File givenFile = new File("." + File.separator + ".." + File.separator + "." + File.separator + "fakeFilename"); //The file or dir we want the parent of, whether it exists or not
File parentFile = new File(givenFile.getAbsolutePath() + File.separator + "..");
System.out.println(parentFile.getAbsolutePath());
Note that this answer assumes you want the actual parent directory on the filesystem, and not a File object representing the parent node of the given File object (which may be null, or may be the same directory as the given file).
EDIT: Also note that the internal filename is not succinct, and could in some cases grow with repeated usage. An equivalent solution without that issue would need to parse the entire absolute filename given by the above solution, and adjust the output, removing all instances of "." and ".." (the latter ofc would need to also remove the node before it, but only after all "." are removed)