1

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

1
  • @Leviand using utility class helped me to read property,but i am trying to read URL(ex: C:\Users\amit\Upload Folder Location), property value from prop.getProperty(property); is without \ i.e (C:UsersamitUpload Folder Location) URL.How to read URL property from property file Commented Jul 25, 2018 at 14:14

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

It helped me to read property,but i am trying to read URL(ex: C:\Users\amit\Upload Folder Location), property value from prop.getProperty(property); is without \ i.e (C:UsersamitUpload Folder Location) URL.How to read URL property from property file
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.