Java FileNotFoundException 尽管文件存在
Java FileNotFoundException although file is there
我设置方法来try/catch这个错误。我的问题是它捕获 Trivia.txt 的 fileNotFoundException,即使我在同一个包中明确创建 Trivia.txt 也是如此。我不知道为什么找不到该文件。我四处寻找问题的答案,但没有运气。不管怎样,这是我的代码
public static void readFile(){
try{
File file = new File("Trivia.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
System.out.println();
}
catch(IOException e){
System.out.println("error reading file");
}
}
这里的代码只是TextHandlerclass的一个方法,被WindowCompclass静态调用(完全无关class)。该包是 mainPackage,其中包含 main() 和 WindowComp() 以及 textHandler() 以及 Triva.Txt
您打开文件的方式,应该是在当前工作目录中找到它,而不是在找到源代码的子目录中。
尝试 System.out.println(file.getCanonicalPath())
以找出代码期望文件的位置。
尝试像这样将您的文件加载为资源
URL fileURL = this.getClass().getResource("Trivia.txt");
File file = new File(fileURL.getPath());
这将从加载资源的 class 的同一个包中加载您的文件。
您还可以使用
为您的文件提供绝对路径
URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt");
如果发现文件远离class当前包的某个地方,你也可以直接向构造函数提供绝对路径:
File file = new File("path/to/file/Trivia.txt");
您还可以使用不同的构造函数,例如此答案中指出的构造函数:
Java - creating new file, how do I specify the directory with a method?
有关更多信息,请参阅文档:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html
我设置方法来try/catch这个错误。我的问题是它捕获 Trivia.txt 的 fileNotFoundException,即使我在同一个包中明确创建 Trivia.txt 也是如此。我不知道为什么找不到该文件。我四处寻找问题的答案,但没有运气。不管怎样,这是我的代码
public static void readFile(){
try{
File file = new File("Trivia.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
System.out.println();
}
catch(IOException e){
System.out.println("error reading file");
}
}
这里的代码只是TextHandlerclass的一个方法,被WindowCompclass静态调用(完全无关class)。该包是 mainPackage,其中包含 main() 和 WindowComp() 以及 textHandler() 以及 Triva.Txt
您打开文件的方式,应该是在当前工作目录中找到它,而不是在找到源代码的子目录中。
尝试 System.out.println(file.getCanonicalPath())
以找出代码期望文件的位置。
尝试像这样将您的文件加载为资源
URL fileURL = this.getClass().getResource("Trivia.txt");
File file = new File(fileURL.getPath());
这将从加载资源的 class 的同一个包中加载您的文件。
您还可以使用
为您的文件提供绝对路径URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt");
如果发现文件远离class当前包的某个地方,你也可以直接向构造函数提供绝对路径:
File file = new File("path/to/file/Trivia.txt");
您还可以使用不同的构造函数,例如此答案中指出的构造函数:
Java - creating new file, how do I specify the directory with a method?
有关更多信息,请参阅文档: https://docs.oracle.com/javase/7/docs/api/java/io/File.html