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

FileReader throws exception because files path has wrong syntax?

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

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

当运行下面的代码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();

您可以通过创建 InputStreamReader 来避免该文件。

InputStreamReader reader = new InputStreamReader(
    this.getClass().getResourceAsStream("/graphqls/test.graphqls"), 
    StandardCharsets.UTF_8
);

建议使用 YourClassName.class.getResourceAsStream() 除非您有某些特定原因使用 .getClass && .getClassLoader。