java - FileReader 抛出异常,因为文件路径语法错误?

标签 java filereader filenotfoundexception

我将要读取的文件放入我的资源文件夹中

src
|_main
   |_resources
     |_graphqls
       |_test.graphqls

以下代码片段读取文件

final String pathToSchemaFile = this.getClass().getClassLoader().getResource("graphqls/test.graphqls").getFile();
final File = new File(pathToSchemaFile);

这是我在评估前面代码片段中 .getFile() 返回的 File 对象时得到的结果。

file:\C:\maven_repository\com\...\app.jar!\graphqls\test.graphqls

enter image description here

运行以下代码时new FileReader(file) 抛出此异常

Method threw 'java.io.FileNotFoundException' exception.
file:\C:\maven_repository\com\...\app.jar!\graphqls\test.graphqls (The filename, directory name, or volume label syntax is incorrect)
java.io.FileNotFoundException: file:\C:\maven_repository\com\...\app.jar.jar!\graphqls\test.graphqls (The filename, directory name, or volume label syntax is incorrect)

最佳答案

您正在访问的文件实际上位于 JAR 文件(如 ZIP)内。

如果您的 jar 位于类路径中:

InputStream is = YourClass.class.getResourceAsStream("1.txt");

如果它不在类路径上,那么您可以通过以下方式访问它:

URL url = new URL("jar:file:/absolute/location/of/yourJar.jar!/1.txt");
InputStream is = url.openStream();

关于java - FileReader 抛出异常,因为文件路径语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248903/

相关文章:

java - 我收到文件未找到异常,我不知道为什么路径是正确的

java - Spring xml到java配置: how to convert nested xml bean definition

java - 如何将列表与其他 UI 元素一起包含在内? (安卓)

java - JVM 内存调优建议

javascript - Meteor:在客户端使用 FileReader 上传图像文件,在服务器上使用 Npm.require ("fs")

jquery - 通过 AJAX Post 将文件输入作为 FileReader 二进制数据发布

java - 为什么无法读取此代码 : Exception in thread "main" java. util.NoSuchElementException,位于 java.util.Scanner.throwFor(未知来源),

java - 无法让 JApplet 工作。每次运行该程序时都会出现错误

java - 文件未找到异常,不知道是什么原因

java - 为什么在尝试使用 log4j 写入文件时会出现此 FileNotFoundException?