gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:10:31 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com