获取 Java 中的绝对目录路径?

Getting absolute directory path in Java?

我需要获取其中一个目录的绝对路径。所以我单击属性以获取该绝对路径并在我的代码中包含:

 Scanner sc = new Scanner(System.in);

 public void Find(String path) {
        System.out.println("Enter in location");

        path = sc.nextLine();
        try 
        {
            File inputFile = new File(path);
            Scanner reader = new Scanner(inputFile);
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Try again file not found");
        }
    }

我试图通过用户输入获取目录的绝对路径,所以我通过在 main 方法中调用 class 通过用户输入输入目录的绝对路径,我得到:

Enter in location of file 
C:\Users\Trevor's PC\Documents\NetBeansProjects
Try again file not found

所以我的 class 或我尝试阅读它的方式一定有问题?

inputFile.getAbsolutePath();

试试这个获取绝对路径

您无法将目录传递给扫描仪以及您在尝试什么。

File f = new File(fname); 
 //apply File class methods on File object 
    System.out.println("File name :"+f.getName()); 
    System.out.println("Path: "+f.getPath()); 
    System.out.println("Absolute path:" +f.getAbsolutePath()); 
    System.out.println("Parent:"+f.getParent()); 
    System.out.println("Exists :"+f.exists()); 
    if(f.exists()) 
    { 
        System.out.println("Is writeable:"+f.canWrite()); 
        System.out.println("Is readable"+f.canRead()); 
        System.out.println("Is a directory:"+f.isDirectory()); 
        System.out.println("File Size in bytes "+f.length()); 
    }