这是我的文件目录
我正在尝试打开 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");
}
}
最佳答案
通常,当您通过 IDE 启动应用程序时,它们会将当前目录设置为项目的根目录,因此您需要从那里传递相对路径
您可以通过以下方式检查设置为当前目录的内容
System.out.println(System.getProperty("user.dir"));
此外,只要文件作为真实文件存在,它就会工作,如果您将其捆绑在 jar 或其他形式的存档中,它将停止工作,所以最好 read it as Resource from classpath
关于java - 尽管文件位于同一目录中,但无法打开文件进行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22792449/