How do I get a file's directory using the File object?

后端 未结 9 2055
半阙折子戏
半阙折子戏 2020-12-08 18:02

Consider the code:

File file = new File(\"c:\\\\temp\\\\java\\\\testfile\");

testfile is a file, and it may or may not exist.

9条回答
  •  情歌与酒
    2020-12-08 18:44

    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 ");
    }
    

提交回复
热议问题