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

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;
}
}
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 : https://github.com/johnsanthosh/image-service to figure out the right way to run this from a JAR.
Answer from John on Stack OverflowAfter 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

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;
}
}
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 : https://github.com/johnsanthosh/image-service to figure out the right way to run this from a JAR.
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:
File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);
Also, that might be helpful reading:
- What is the difference between Class.getResource() and ClassLoader.getResource()?
- Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar
- Loading resources using getClass().getResource()
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:
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:
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:
String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");
While injecting a File is generally the preferred approach, you can also leverage Spring's ResourceLoader for dynamic loading of resources.
Generally this is as simple as injecting the ResourceLoader into your Spring bean:
@Autowired
private ResourceLoader resourceLoader;
Then to load from the classpath:
resourceLoader.getResource("classpath:myfile.txt");
Since OP is injecting Only the fileName through spring, still want to create the File Object through code , You should Use ClassLoadeer to read the file
Try this
InputStream is = HandleData.class.getClassLoader().getResourceAsStream(getFile()));
Edit
Heres the remainder of code , to read the file
BufferedInputStream bf = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bf);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
Edit 2
Since you want it as File Object, to get hold of the FileInputStream
try this
FileInputStream fisTargetFile = new FileInputStream(new File(HandleData.class.getClassLoader().getResource(getFile()).getFile()));
I just ran into this. I'm using Maven. I took a look at my target/test-classes folder and my resource file wasn't in there (even though it was in my src/test/resources folder).
I ran mvn clean install and then rechecked my target/test-classes folder and the resource file was now there. After that, my test was able to find the file and the test worked.
So it seems that your resources aren't copied until you do a mvn clean. JUnit is looking in the classpath built by maven and until the file actually makes it into the target/test-classes folder, JUnit won't be able to find it.
You can't access a @Value resource unless it is a property defined. It should be this way.
@Value("${stateJsonPath}")
Resource stateFile;
If you have to get the resource from a hardcoded path then use this way:
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
//...
Resource stateFile = new ClassPathResource("state.json");