Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 706 Vote(s) - 3.45 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read file from resources folder in Spring Boot

#1
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 tried a few different ways but I can't get it to work. This is my code.

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);

This is the location of the file.

[![enter image description here][1]][1]

And here I can see the file in the `classes` folder.

[![enter image description here][2]][2]

But when I run the code I get the following error.

jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory)

What is it I'm doing wrong in my code?

[1]:

[2]:
Reply

#2
create json folder in resources as subfolder then add json file in folder then you can use this code :
[![enter image description here][1]][1]


`import com.fasterxml.jackson.core.type.TypeReference;`


`InputStream is = TypeReference.class.getResourceAsStream("/json/fcmgoogletoken.json");`

this works in Docker.


[1]:
Reply

#3
if you have for example config folder under Resources folder
I tried this Class working perfectly hope be useful


File file = ResourceUtils.getFile("classpath:config/sample.txt")

//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
Reply

#4
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");

Reply

#5
See my answer here:

[To see links please register here]


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
Reply

#6
Spent way too much time coming back to this page so just gonna leave this here:

File file = new ClassPathResource("data/data.json").getFile();

Reply

#7
After spending a lot of time trying to resolve this issue, finally found a solution that works. The solution makes use of Spring's ResourceUtils.
Should work for json files as well.

Thanks for the well written page by Lokesh Gupta : [Blog][1]

[![enter image description here][2]][2]


<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-java -->

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;
}
}


<!-- end snippet -->


[1]:

[To see links please register here]

[2]:


To answer a few concerns on the comments :

Pretty sure I had this running on Amazon EC2 using `java -jar target/image-service-slave-1.0-SNAPSHOT.jar`

Look at my github repo :

[To see links please register here]

to figure out the right way to run this from a JAR.
Reply

#8
Below is my working code.
```
List<sampleObject> list = new ArrayList<>();
File file = new ClassPathResource("json/test.json").getFile();
ObjectMapper objectMapper = new ObjectMapper();
sampleObject = Arrays.asList(objectMapper.readValue(file, sampleObject[].class));
```
Hope it helps one!
Reply

#9
For me, the bug had two fixes.

1. Xml file which was named as SAMPLE.XML which was causing even the below solution to fail when deployed to aws ec2. The fix was to rename it to new_sample.xml and apply the solution given below.
2. Solution approach

[To see links please register here]


I was using Spring boot as jar and deployed to aws ec2
Java variant of the solution is as below :

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;


public class XmlReader {

private static Logger LOGGER = LoggerFactory.getLogger(XmlReader.class);

public static void main(String[] args) {


String fileLocation = "classpath:cbs_response.xml";
String reponseXML = null;
try (ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext()){

Resource resource = appContext.getResource(fileLocation);
if (resource.isReadable()) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(resource.getInputStream()));
Stream<String> lines = reader.lines();
reponseXML = lines.collect(Collectors.joining("\n"));

}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}


Reply

#10
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][1] 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"));


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through