Chris
Chris

Reputation: 1505

Trouble Reading from Properties File

I'm building a Java program that will automatically run a hundred or so tests. The program itself is in its final stages of production, and my boss wants me to take out all hard-coded variables and store them in a .properties file. Right now I have two java files Logic.java and Tests.java, and a properties files xxx.properties. However when I run the code (JUnit tests in Tests.java), it appears that the properties never get loaded. Relevant code follows:

In Logic.java

Properties properties = new Properties();

String val1;
String val2;
...
String last_val;

public void importProperties() {
  try {
    properties.load(new FileInputStream("xxx.properties"));
    val1 = properties.getProperty("val1-property-name");
    ...
    lastVal = properties.getProperty("lastVal-property-name");
  } catch (Exception e) {
    e.printStackTrace();
  }
}

public void test() {
   importProperties();
   //Testing code follows, several method calls referencing val1, val2, etc
}

In Tests.java

Logic logic = new Logic();

@Before
public void before() {
    logic.importProperties();
}

@Test
public void test1() {
  logic.testMethod();
}

//More tests

}

I should be importing the properties and setting the string vals in Logic.java in the @Before method since I'm not creating a new instance of Logic (or so I believe), but when I try to find the values of the strings (writing the string values to a log file), there's no text in said file. I know for a fact that the log file writing works, so the Strings aren't being set to their property values. My property file is also correctly written, I can provide more information if necessary. Thanks!

Edit: So after a bunch of troubleshooting it looks as if the properties file is definitely being read since a properties.keys() call returns all the keys. It's not setting the strings the the key values, however. Still troubleshooting but any ideas would be helpful

Upvotes: 1

Views: 230

Answers (2)

mprabhat
mprabhat

Reputation: 20323

I think your properties file is not being found and thats the whole issue.

Instead of creating a new FileInputStream try to use below lines of code

properties.load(this.getClass().getResourceAsStream("xxx.properties"));

Upvotes: 0

Ehsan Khodarahmi
Ehsan Khodarahmi

Reputation: 4922

replace

properties.load(new FileInputStream("xxx.properties"));

with

properties.load(new InputStreamReader(Logic.class.getResource("xxx.properties").openStream(), "UTF8"));

& test again. I hope it solves your problem

Upvotes: 1

Related Questions