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

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

    You can use this

     File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
    
    0 讨论(0)
  • 2020-12-08 18:28

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

    File file = new File("\\TestHello\\test.txt");
    System.out.println(file.getAbsoluteFile());
    
    0 讨论(0)
  • 2020-12-08 18:34
    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());
    }
    
    0 讨论(0)
  • 2020-12-08 18:37

    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.

    0 讨论(0)
  • 2020-12-08 18:38

    File.getParent() from Java Documentation

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