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

#11
stuck in the same issue, this helps me

URL resource = getClass().getClassLoader().getResource("jsonschema.json");
JsonNode jsonNode = JsonLoader.fromURL(resource);
Reply

#12
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
Reply

#13
If you're using `spring` and `jackson` (most of the larger applications will), then use a simple oneliner:

`JsonNode json = new ObjectMapper().readTree(new ClassPathResource("filename").getFile());`
Reply

#14
Very short answer: you are looking for the resource in the scope of a classloader's class instead of your target class. This should work:
```java
File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);
```
Also, that might be helpful reading:

-

[To see links please register here]

-

[To see links please register here]

-

[To see links please register here]


P.S. there is a case when a project compiled on one machine and after that launched on another or inside Docker. In such a scenario path to your resource folder would be invalid and you would need to get it in runtime:

```java
ClassPathResource res = new ClassPathResource("jsonschema.json");
File file = new File(res.getPath());
JsonNode mySchema = JsonLoader.fromFile(file);
```

***Update from 2020***

On top of that if you want to read resource file as a String, for example in your tests, you can use these static utils methods:

```java
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);
}
```

Example of usage:
```java
String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");
```
Reply

#15
Spring provides `ResourceLoader` which can be used to load files.

```
@Autowired
ResourceLoader resourceLoader;


// path could be anything under resources directory
File loadDirectory(String path){
Resource resource = resourceLoader.getResource("classpath:"+path);
try {
return resource.getFile();
} catch (IOException e) {
log.warn("Issue with loading path {} as file", path);
}
return null;
}
```

Referred to this [link][1].


[1]:

[To see links please register here]

Reply

#16
If you are using maven resource filter in your proyect, you need to configure what kind of file is going to be loaded in pom.xml. If you don't, no matter what class you choose to load the resource, it won't be found.

pom.xml

<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
<include>**/*.yml</include>
<include>**/*.yaml</include>
<include>**/*.json</include>
</includes>
</resource>
</resources>
Reply

#17
Below works in both IDE and running it as a jar in the terminal,

import org.springframework.core.io.Resource;

@Value("classpath:jsonschema.json")
Resource schemaFile;

JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema jsonSchema = factory.getSchema(schemaFile.getInputStream());
Reply

#18
I had same issue and because I just had to get file path to send to file input stream, I did this way.


String pfxCertificate ="src/main/resources/cert/filename.pfx";
String pfxPassword = "1234";
FileInputStream fileInputStream = new FileInputStream(pfxCertificate));
Reply

#19
Using Spring **ResourceUtils.getFile()** you don't have to take care absolute path :)

private String readDictionaryAsJson(String filename) throws IOException {
String fileContent;
try {
File file = ResourceUtils.getFile("classpath:" + filename);
Path path = file.toPath();
Stream<String> lines = Files.lines(path);
fileContent = lines.collect(Collectors.joining("\n"));
} catch (IOException ex) {
throw ex;
}
return new fileContent;
}
Reply

#20
### How to get resource reliably

To reliably get a file from the resources in Spring Boot application:

1. Find a way to pass abstract resource, for example, `InputStream`, `URL` instead of `File`
1. Use framework facilities to get the resource

## Example: read file from `resources`

```java
public class SpringBootResourcesApplication {
public static void main(String[] args) throws Exception {
ClassPathResource resource = new ClassPathResource("/hello", SpringBootResourcesApplication.class);
try (InputStream inputStream = resource.getInputStream()) {
String string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(string);
}
}
}
```

* [`ClassPathResource`](

[To see links please register here]

) is Spring's implementation of `Resource` - the abstract way to load _resource_. It is instantiated using the [`ClassPathResource(String, Class<?>)`](

[To see links please register here]

) constructor:
* `/hello` is a path to the file
* The leading slash loads file by absolute path in classpath
* It is required because otherwise the path would be relative to the class
* If you pass a `ClassLoader` instead of `Class`, the slash can be omitted
* See also [What is the difference between Class.getResource() and ClassLoader.getResource()?](

[To see links please register here]

)
* The second argument is the `Class` to load the resource by
* Prefer passing the `Class` instead of `ClassLoader`, because [`ClassLoader.getResource` differs from `Class.getResource` in JPMS](

[To see links please register here]

)

* Project structure:
```
├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
└── main
├── java
│ └── com
│ └── caco3
│ └── springbootresources
│ └── SpringBootResourcesApplication.java
└── resources
├── application.properties
└── hello
```

The example above works from both IDE and jar

#### Deeper explanation

###### Prefer abstract resources instead of `File`

* Examples of abstract resources are `InputStream` and `URL`
* Avoid using `File` because it is not always possible to get it from a classpath resource
* E.g. the following code works in IDE:
```java
public class SpringBootResourcesApplication {
public static void main(String[] args) throws Exception {
ClassLoader classLoader = SpringBootResourcesApplication.class.getClassLoader();
File file = new File(classLoader.getResource("hello").getFile());

Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)
.forEach(System.out::println);
}
}
```
but fails with:
```
java.nio.file.NoSuchFileException: file:/home/caco3/IdeaProjects/spring-boot-resources/target/spring-boot-resources-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/hello
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
```
when Spring Boot jar run
* If you use external library, and it asks you for a resource, try to find a way to pass it an `InputStream` or `URL`
* For example the `JsonLoader.fromFile` from the question could be replaced with [`JsonLoader.fromURL`](

[To see links please register here]

) method: it accepts `URL`

###### Use framework's facilities to get the resource:

Spring Framework enables access to classpath resources through [`ClassPathResource`](

[To see links please register here]

)

You can use it:

1. Directly, as in the example of reading file from `resources`
1. Indirectly:
1. Using [`@Value`](

[To see links please register here]

):
```java
@SpringBootApplication
public class SpringBootResourcesApplication implements ApplicationRunner {
@Value("classpath:/hello") // Do not use field injection
private Resource resource;

public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootResourcesApplication.class, args);
}

@Override
public void run(ApplicationArguments args) throws Exception {
try (InputStream inputStream = resource.getInputStream()) {
String string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(string);
}
}
}
```
1. Using [`ResourceLoader`](

[To see links please register here]

):
```java
@SpringBootApplication
public class SpringBootResourcesApplication implements ApplicationRunner {
@Autowired // do not use field injection
private ResourceLoader resourceLoader;

public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootResourcesApplication.class, args);
}

@Override
public void run(ApplicationArguments args) throws Exception {
Resource resource = resourceLoader.getResource("/hello");
try (InputStream inputStream = resource.getInputStream()) {
String string = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
System.out.println(string);
}
}
}
```
* See also [this](

[To see links please register here]

) answer
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

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