Quarkus读取resources目录JSON文件报错,求Alexa APL技能开发协助
问题分析与解决方法
核心错误:代码中
new File(inputStream.toString())是错误写法。InputStream.toString()返回的是输入流对象的字符串标识(类似java.io.FileInputStream@1234abcd),并非文件路径,这会导致ObjectMapper尝试读取不存在的文件,触发IO异常。修正后的代码:直接使用ObjectMapper读取InputStream即可,无需转换为File对象。同时优化类加载器获取方式,增加文件存在性校验:
try(InputStream inputStream = YourClass.class.getClassLoader().getResourceAsStream("documents/helloWorldDocument.json")) { if (inputStream == null) { throw new AskSdkException("helloWorldDocument.json not found in resources/documents"); } // Retrieve the JSON document and put into a string/object map ObjectMapper mapper = new ObjectMapper(); TypeReference<HashMap<String, Object>> documentMapType = new TypeReference<HashMap<String, Object>>() {}; Map<String, Object> document = mapper.readValue( inputStream, documentMapType); // Use builder methods in the SDK to create the directive. RenderDocumentDirective renderDocumentDirective = RenderDocumentDirective.builder() .withToken("helloWorldToken") .withDocument(document) .build(); // Add the directive to a responseBuilder. responseBuilder.addDirective(renderDocumentDirective); // Tailor the speech for a device with a screen. speechText.append(" You should now also see my greeting on the screen."); } catch (IOException e) { throw new AskSdkException("Unable to read or deserialize the hello world document", e); }
- 额外注意事项:
- 确认
src/main/resources/documents/helloWorldDocument.json文件存在,且路径大小写与代码完全一致(Quarkus打包后资源路径区分大小写)。 YourClass需替换为当前代码所在的类名,避免类加载器获取失败。
- 确认
内容的提问来源于stack exchange,提问作者Hamid Mohamadi
相关产品推荐
相关产品推荐

