I\'m using Spring Boot and json-schema-validator
. I\'m trying to read a file called jsonschema.json
from the resources
folder. I\'ve t
Spent way too much time coming back to this page so just gonna leave this here:
File file = new ClassPathResource("data/data.json").getFile();
Here is my solution. May help someone;
It returns InputStream, but i assume you can read from it too.
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jsonschema.json");
stuck in the same issue, this helps me
URL resource = getClass().getClassLoader().getResource("jsonschema.json");
JsonNode jsonNode = JsonLoader.fromURL(resource);
The simplest method to bring a resource from the classpath in the resources directory parsed into a String is the following one liner.
As a String(Using Spring Libraries):
String resource = StreamUtils.copyToString(
new ClassPathResource("resource.json").getInputStream(), defaultCharset());
This method uses the StreamUtils utility and streams the file as an input stream into a String in a concise compact way.
If you want the file as a byte array you can use basic Java File I/O libraries:
As a byte array(Using Java Libraries):
byte[] resource = Files.readAllBytes(Paths.get("/src/test/resources/resource.json"));
See my answer here: https://stackoverflow.com/a/56854431/4453282
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
Use these 2 imports.
Declare
@Autowired
ResourceLoader resourceLoader;
Use this in some function
Resource resource=resourceLoader.getResource("classpath:preferences.json");
In your case, as you need the file you may use following
File file = resource.getFile()
Reference:http://frugalisminds.com/spring/load-file-classpath-spring-boot/ As already mentioned in previous answers don't use ResourceUtils it doesn't work after deployment of JAR, this will work in IDE as well as after deployment
i think the problem lies within the space in the folder-name where your project is placed. /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json
there is space between Java Programs.Renaming the folder name should make it work