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

后端 未结 9 2054
半阙折子戏
半阙折子戏 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:46

    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();
    
    0 讨论(0)
  • 2020-12-08 18:49
    String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length()); 
    

    This would be my solution

    0 讨论(0)
  • 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(), "");
    }
    
    0 讨论(0)
提交回复
热议问题