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

后端 未结 9 2077
半阙折子戏
半阙折子戏 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条回答
  •  旧时难觅i
    2020-12-08 18:52

    File filePath=new File("your_file_path");
    String dir="";
    if (filePath.isDirectory())
    {
        dir=filePath.getAbsolutePath();
    }
    else
    {
        dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
    }
    

提交回复
热议问题