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

后端 未结 9 2076
半阙折子戏
半阙折子戏 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: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());
    }
    

提交回复
热议问题