我使用的是Spring Boot和json-schema-validator。我正在尝试从resources文件夹中读取一个名为jsonschema.json的文件。我已经尝试了几种不同的方法,但我不能让它工作。这是我的代码。
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);这是文件的位置。

在这里我可以看到classes文件夹中的文件。

但是当我运行代码时,我得到了以下错误。
jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory)我在代码中做错了什么?
发布于 2018-03-25 02:22:23
在花了很多时间尝试解决这个问题之后,终于找到了一个可行的解决方案。该解决方案利用了Spring的ResourceUtils。应该也适用于json文件。
感谢Lokesh Gupta写得很好的页面:Blog

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;
public class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());
public static Properties fetchProperties(){
Properties properties = new Properties();
try {
File file = ResourceUtils.getFile("classpath:application.properties");
InputStream in = new FileInputStream(file);
properties.load(in);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return properties;
}
}为了回答评论中的一些问题:
我非常确定我已经使用java -jar target/image-service-slave-1.0-SNAPSHOT.jar在亚马逊EC2上运行了这段代码
查看我的github代码库:https://github.com/johnsanthosh/image-service,找出从JAR运行它的正确方法。
发布于 2017-06-07 04:45:58
非常简短的回答:您要在类加载器的类的作用域中查找资源,而不是在目标类中查找。这应该是可行的:
File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);此外,这可能是有帮助的阅读:
附注:有这样一种情况,项目在一台机器上编译,然后在另一台机器上或在Docker内部启动。在这种情况下,资源文件夹的路径将是无效的,您需要在运行时获取它:
ClassPathResource res = new ClassPathResource("jsonschema.json");
File file = new File(res.getPath());
JsonNode mySchema = JsonLoader.fromFile(file);2020年的更新
最重要的是,如果你想以字符串的形式读取资源文件,例如在你的测试中,你可以使用这些静态utils方法:
public static String getResourceFileAsString(String fileName) {
InputStream is = getResourceFileAsInputStream(fileName);
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
return (String)reader.lines().collect(Collectors.joining(System.lineSeparator()));
} else {
throw new RuntimeException("resource not found");
}
}
public static InputStream getResourceFileAsInputStream(String fileName) {
ClassLoader classLoader = {CurrentClass}.class.getClassLoader();
return classLoader.getResourceAsStream(fileName);
}用法示例:
String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");发布于 2018-10-31 12:03:21
例如,如果你在Resources文件夹下有config文件夹,我尝试过这个类,我希望它能帮上忙
File file = ResourceUtils.getFile("classpath:config/sample.txt")
//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);https://stackoverflow.com/questions/44399422
复制相似问题