从JAR访问资源文件

时间:2019-01-22 12:57:48

标签: java spring spring-boot

我在资源中有一个JSON模式文件,我需要将其与DB的返回JSON值进行比较。我正在为我的Rest API使用SpringBoot RestController。我有代码在Intellij中工作,但什么时候 我正在从罐子里跑。

File schemaFile = new File(ProductUtil.class.getClassLoader().getResource("com/some/package/schema/schema.json").toURI()); //working in Intellij but not in jar
File schemaFile = new File(ProductUtil.class.getClassLoader().getResource("/com/some/package/schema/schema.json").toPath()); //working in Intellij but not in jar

获取以下异常

java.io.FileNotFoundException: file:/app.jar!/BOOT-INF/classes!/com/some/package/schema/schema.json (No such file or directory)

我也尝试过使用getResourceAsStream,但它也抱怨文件路径。现在我不确定该怎么办。

 InputStream schemaFileStream = ProductUtil.class.getClassLoader().getResourceAsStream(jsonSchemaPath);
            byte[] buffer = new byte[schemaFileStream.available()];
            schemaFileStream.read(buffer);

            File targetSchemaFile = new File("com/nielsen/media/adeui/product/schema/targetFile.json");
            OutputStream outStream = new FileOutputStream(targetSchemaFile);
            outStream.write(buffer);

任何帮助表示赞赏。谢谢。

0 个答案:

没有答案