122

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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Koerr
  • 15,215
  • 28
  • 78
  • 108

10 Answers10

196

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

Additionally, if you want to find out whether the original File does exist and is a directory, then exists() and isDirectory() are what you're after.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 11
    Use file.getParent() carefully, because it may return null in some cases. – geschema Jul 22 '14 at 09:02
  • @geschema Ponaguynik's answer below addresses this – a113nw Jun 13 '17 at 19:27
  • This (and all other current answers as of posting) fail to give the parent directory (in terms of the filesystem) if the given file is eg. new File("." + File.separator + "."); See my answer below for a more robust solution if needed – Laike Endaril Jun 11 '21 at 01:22
  • `System.out.println(new File("\\myfile.txt").getParentFile().getAbsolutePath());` correctly prints "C:\" but careful when you're using a `File` with a path like that because some libraries that write/read files might not be able to handle paths starting with an e.g. backslash or a ".." (which is also theoretically valid). It's best to check all the possibilities mentioned [here](https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats). – Neph Feb 22 '22 at 09:43
27

File.getParent() from Java Documentation

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76
Joel
  • 29,538
  • 35
  • 110
  • 138
25

If you do something like this:

File file = new File("test.txt");
String parent = file.getParent();

parent will be null.

So to get directory of this file you can do next:

parent = file.getAbsoluteFile().getParent();
Ponaguynik
  • 711
  • 7
  • 5
9

File API File.getParent or File.getParentFile should return you Directory of file.

Your code should be like :

    File file = new File("c:\\temp\\java\\testfile");
    if(!file.exists()){
        file = file.getParentFile();
    }

You can additionally check your parent file is directory using File.isDirectory API

if(file.isDirectory()){
    System.out.println("file is directory ");
}
YoK
  • 14,329
  • 4
  • 49
  • 67
3
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
    dir=filePath.getAbsolutePath();
}
else
{
    dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
J Richard Snape
  • 20,116
  • 5
  • 51
  • 79
  • 1
    Descriptions are needed. – Halvor Holsten Strand Mar 03 '15 at 11:08
  • 2
    Welcome to Stack Overflow! In general, code answers need a little explanation - see this meta [Stackoverflow post](http://meta.stackoverflow.com/a/260413/838992). With the answer you've posted, you might need to explain you're trying to give a general case and how it relates to the OP's actual post. More seriously - you might want to consider how it would work on `your_file_path = "C:\\testfiles\\temp\\testfile";` - I don't think it would give what you hope. – J Richard Snape Mar 03 '15 at 12:54
3
File directory = new File("Enter any 
                directory name or file name");
boolean isDirectory = directory.isDirectory();
if (isDirectory) {
  // It returns true if directory is a directory.
  System.out.println("the name you have entered 
         is a directory  : "  +    directory);  
  //It returns the absolutepath of a directory.
  System.out.println("the path is "  + 
              directory.getAbsolutePath());
} else {
  // It returns false if directory is a file.
  System.out.println("the name you have
   entered is a file  : " +   directory);
  //It returns the absolute path of a file.
  System.out.println("the path is "  +  
            file.getParent());
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 2
    You do not answer the question, this does not work for a file. – toni07 Apr 06 '15 at 21:17
  • `code` final File file = new File("C:/dev/changeofseasons.mid"); System.out.println("file exists? " + file.exists()); System.out.println("directory of file: " + file.getAbsolutePath()); Ok, sorry for lame indenting, I don't think it is possible to format code in comments. Still, your code obviously does not work. – toni07 Apr 06 '15 at 21:41
1
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length()); 

This would be my solution

nobes
  • 11
  • 2
0

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)

Laike Endaril
  • 781
  • 5
  • 4
-1

You can use this

 File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
Saurabh
  • 7,525
  • 4
  • 45
  • 46
-1

I found this more useful for getting the absolute file location.

File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());
C.Ikongo
  • 1,706
  • 1
  • 16
  • 15