【问题标题】:Unable to open file for reading though file are in the same directory尽管文件在同一目录中,但无法打开文件进行读取
【发布时间】:2014-04-01 17:09:56
【问题描述】:

这是我的文件目录

我正在尝试打开 admin.dat 进行阅读,但不明白为什么我无法打开文件并且总是抛出 FileNotFound 异常

代码:

public void readfile(){
    try{
        Scanner filereader = new Scanner(new File("admin.dat"));
        String data;

        while(filereader.hasNextLine()){
            data = filereader.nextLine();
            System.out.println(data);
        }
    }
    catch (FileNotFoundException e){
        System.out.println("File not found");
    }
    catch (IOException e){
        System.out.println("Error while reading file");
    }
}

【问题讨论】:

  • 您必须指定从srcbuild 目录所在目录开始的路径。所以src/javaassignment1/admin.dat
  • 尝试将 admin.dat 放在类文件所在的等效位置,这可能是一个名为 bin 的目录。

标签: java exception file-io


【解决方案1】:

通常当您通过 IDE 启动应用程序时,它们会将当前目录设置为项目的根目录,因此您需要从那里传递相对路径

您可以检查设置为当前目录的内容

System.out.println(System.getProperty("user.dir"));

只要文件作为真实文件存在,它就可以工作,如果你将它捆绑在 jar 或其他形式的存档中,它将停止工作,所以最好 read it as Resource from classpath

【讨论】:

  • @JihgarJoshi 谢谢兄弟
猜你喜欢
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多