tech_questions
tech_questions

Reputation: 273

how to read a file from resources folder in properties file

I have a file under resources folder src/test/resources/file.xml and another under src/test/resources/test.properties. I want to set a property in properties file to point to file.xml. How can I achieve this?

Say I have a property

test.file = file.xml

and my java class reads the file as follows:

File cert = new File(fileName); // fileName is the value of test.file

This does not work however.

Upvotes: 0

Views: 5296

Answers (2)

Subburaj
Subburaj

Reputation: 2334

  • Firstly, you need to find the relative path for the resources using below steps
  • Secondly, you can configure and load the test properties file
  • Finally, read the property value and append with the resource
    directory

Code:

String rootDirectory=System.getProperty("user.dir");
String resourceDirectory=rootDirectory+"src/test/resources/";

//Configure property File
Properties properties = new Properties();
properties.load(new FileInputStream(resourceDirectory+"test.properties"));
PropertyConfigurator.configure(properties);

//To get the property value
String tempFileName=properties.getProperty("test.file");

//filename Needs to be changed as below
File cert = new File(resourceDirectory+tempFileName);

Upvotes: 1

Jeffin Manuel
Jeffin Manuel

Reputation: 542

You can use Properties class to read and write to config files.

Upvotes: 2

Related Questions