在 Java Maven 项目中读取现有文件时出现 FileNotFoundException

FileNotFoundException while reading an existing file in Java Maven project

我正在尝试读取 Maven 项目中的现有文件,但它显示 FileNotFoundException。我相信我正确地得到了文件的路径,但我不知道下一步该去哪里。 这是我拥有的:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.company</groupId>
  <artifactId>weather</artifactId>
  <version>1.0</version>

  <name>weather</name>
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.release>15</maven.compiler.release>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

我的 Maven 目录树:

    String fileName = "/weatherstack.json";
    
    String path = getClass().getResource(fileName).getPath();
    
    System.out.println(path);

输出:/Users/.../.../weather/target/classes/weatherstack.json

Reader reader = new FileReader(path);

错误:未处理的异常类型 FileNotFoundException

感谢任何帮助!

您正在调用的 FileReader 构造函数指定 Creates a new FileReader, given the name of the file to read from javadocs。这有点令人困惑,但看起来它接受的是文件名,而不是文件路径。您应该尝试使用其他构造函数,例如:

Reader reader = new FileReader(new File(path));

在给定的图像中,weatherstack.json 文件显示在资源目录中,而在目标文件中,它显示在 类 目录中。删除目标目录并重建项目。

public FileReader​(String fileName) throws FileNotFoundException 意味着您必须:

  • try...catch 方法内的 FNFE 或
  • 在封闭方法的 header.
  • 中声明它

这样就不再是“未处理”了。