【发布时间】:2021-01-10 21:33:16
【问题描述】:
我正在尝试读取 Maven 项目中的现有文件,但它显示 FileNotFoundException。我相信我得到了正确的文件路径,我被困住了,不知道下一步该去哪里。
这是我所拥有的:
- pom.xml:
<?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
感谢任何帮助!
【问题讨论】:
-
您是否尝试过直接进入您目录中的 JSON 文件并复制文件位置?
-
你试过
getClass().getClassLoader().getResource(fileName)吗? -
@AdrianRusso 嗨,阿德里安!我试图从 JSON 文件中“复制路径”,它似乎与我上面得到的输出相同。你知道会出什么问题吗?谢谢!
-
@f1sh 嗨 f1sh!谢谢你的评论。当我尝试
getClass().getClassLoader().getResource(fileName)时,它返回 null :( -
如果从
fileName中删除前导/会怎样?
标签: java maven filereader filenotfoundexception