我将要读取的文件放入我的资源文件夹中
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();
关于java - FileReader 抛出异常,因为文件路径语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248903/