【问题标题】:Getting absolute directory path in Java?在Java中获取绝对目录路径?
【发布时间】:2018-12-27 01:47:27
【问题描述】:

我需要获取我的一个目录的绝对路径。所以我点击属性来获取绝对路径并在我的代码中:

 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方法中调用类通过用户输入输入目录的绝对路径,我得到:

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

所以我的课堂或我试图阅读它的方式一定有问题?

【问题讨论】:

  • 您不能将目录传递给Scanner。你到底想做什么?
  • 顺便说一句,文件夹名称带有撇号是最糟糕的想法

标签: java file directory absolute-path


【解决方案1】:
inputFile.getAbsolutePath();

试试这个获取绝对路径

您无法将目录传递给 Scanner,而您究竟在尝试什么。

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()); 
    } 

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 2023-04-05
    • 2014-01-26
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多