Bilal Dekar
Bilal Dekar

Reputation: 3986

Deployed WAR can't access a file

I have a spring application, and i'm trying to access a json file with the following code :

    try (FileReader reader = new FileReader("parameters.json")) {
        Object obj = jsonParser.parse(reader);
        parameterList = (JSONArray) obj;
    }

I have put the parameter.json file in the project folder and I'm accesing the file data from an angular app through a rest api, and that works fine when I run the application on local machine, but when I deploy the war file on tomcat, my application can't load the file, should I put parameter.json file somewhere else on tomcat or what is the best solution for it.

Upvotes: 0

Views: 1091

Answers (4)

Anonymous Beaver
Anonymous Beaver

Reputation: 419

FileReader is looking for a full-fledged file system like the one on your computer, but when your WAR is deployed, there just isn't one, so you have to use a different approach. You can grab your file directly from your src/main/resources folder like this

InputStream inputStream = getClass().getResourceAsStream("/parameters.json");

Upvotes: 1

Cool Java guy מוחמד
Cool Java guy מוחמד

Reputation: 1727

Make sure your parameters.josn filename is exactly same in the code. Move you parameters.json file in the resources folder and then use the classpath with the filename.

 try (FileReader reader = new FileReader("classpath:parameters.json")) {
   Object obj = jsonParser.parse(reader);
   parameterList = (JSONArray) obj;
 }

Upvotes: 2

Woodchuck
Woodchuck

Reputation: 4464

Your question states you are attempting to access a file called parameter.json, while your code excerpt shows parameters.json. Perhaps that discrepancy indicates a typo in your source code?

If not, there are various ways to access a file from the classpath in Spring, with the first step for each being to ensure the file is in the project's src/main/resources directory.

You can then use one of the Spring utility classes ClassPathResource, ResourceLoader or ResourceUtils to get to the file. The easiest approach, though, may be to put your properties in a .properties file (default file name application.properties) and access the values using Spring's @Value annotation:

@Value("${some.value.in.the.file}")
private String myValue;

You can use other file names as well by utilizing @PropertySource:

@Configuration
@PropertySource(value = {"classpath:application.properties", 
    "classpath:other.properties"})
public class MyClass {

    @Value("${some.value.in.the.file}")
    private String myValue;

    ...
}

Upvotes: 2

Dhruv
Dhruv

Reputation: 157

Try to put the file under resources folder in your spring project. You should be able to access the file from that location.

Upvotes: 1

Related Questions