Java FileNotFound异常错误,即使我指定了正确的路径

7xllpg7q  于 2023-03-16  发布在  Java
关注(0)|答案(2)|浏览(132)

找不到该文件,我不必指定文件位置,因为它与类Test位于同一目录中。
代码:

File myFile = new File("aaa.txt");
    boolean isExisting = myFile.exists();
    System.out.println(isExisting); 
    

    try {
        
        FileReader f = new FileReader(myFile); 
        BufferedReader bf = new BufferedReader(f); 
        
        
        
        
        
      String line = bf.readLine();
      
      while(line != null) {
          
          System.out.println(line); 
          line = bf.readLine(); 
          
      }
      
      bf.close(); 
      
    } catch (FileNotFoundException e) {
        
        System.out.println("Can't find file");
        
        //e.printStackTrace(); 
        
        
    } catch (IOException e) {
        
        System.out.println("Error");
        
        
    }

错误(如果未捕获):

java.io.FileNotFoundException: aaa.txt (The specified file cannot be found)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileReader.<init>(FileReader.java:75)
at Testing/Packageeee.Test.main(Test.java:29)

它们都在同一个目录中

v2g6jxz6

v2g6jxz61#

在主类上使用getResourceAsStream为文件获取InputStream

BufferedReader bf = new BufferedReader(new InputStreamReader(
                        Test.class.getResourceAsStream("aaa.txt")));
eit6fx6z

eit6fx6z2#

几乎可以肯定,您是从项目的根目录运行的,而不是从文本文件所在的目录运行的。
假设aaa.txt位于名为src的目录中,下面的代码段应该可以工作:

String baseDirectory;
  try {
    baseDirectory = new File("./src").getCanonicalPath();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  

  File myFile = new File(baseDirectory, "aaa.txt");

相关问题