Reputation: 37
I am trying to read a property file from src/main/resources
in my Java web application.
The problem is when i tried to load the file using below code
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
Its trying to fetch file form target classes ad getting Exception
java.io.FileNotFoundException: C:\Users\PL90169\Java%20Projects\MKPFileUploadService\target\classes\config.properties".
How to change file reading directory from target to source folder instead of target. Attached project structure here
Upvotes: 1
Views: 2194
Reputation: 92
May be you want this:
InputStream inputStream = getClass().getResourceAsStream("/config.properties");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
byte[] buffer = new byte[4 * 1024];
while (true) {
int readCount = inputStream.read(buffer);
if (readCount < 0) break;
bOut.write(buffer, 0, readCount);
}
String configContent = bOut.toString("UTF-8");
Upvotes: 0
Reputation: 2805
I suggest you building an utility class, so you can easly load all properties that you need, something like:
public static String getPropertyValue(String property) throws IOException {
Properties prop = new Properties();
String propFileName = "config.properties";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
return prop.getProperty(property);
}
So if in your config.properties
file you put something like
exampleValue=hello
when you call getPropertyValue("exampleValue")
you will get hello
Upvotes: 1