user5520049
user5520049

Reputation:

Reading from config.properties file Maven project

I'm new in maven and java , i imported maven project , it has config.properties file , this file contains

PATH_TO_QUERY_FILE=abc.txt

and class that using the property from the config.properties like

queryFile = prop.getProperty("PATH_TO_QUERY_FILE");

Should i add real path for this file in config to make code read it while running ? like

PATH_TO_QUERY_FILE=/home/user/workspace/project/abc.txt 

or not ?

enter image description here

Coder used this statements

FileInputStream finputstream = new FileInputStream( "/home/user/workspace/project/config.properties"); prop.load(finputstream); queryFile = prop.getProperty("PATH_TO_QUERY_FILE"); fos = new FileOutputStream(new File( prop.getProperty("PATH_TO_OUTPUT_FILE"))); finputstream.close();

Upvotes: 4

Views: 24670

Answers (1)

Dzmitry Paulenka
Dzmitry Paulenka

Reputation: 1919

It depends on how you're planning to distribute your application. And on how you're reading the files. Basically there'are two options: reading from files and reading from classpath.

1. Reading from files.

If you're using this path by passing it to a File constructor or passing to some FileStream, than you should know that your paths will be resolved relative to working folder. Working folder is basically the one, from which you initiate java -cp .. some.MainClass command. In that case you will have to copy config.properties file with you and run your command from appropriate directory. File configs are more flexible in a way, that you will not have to rebuild your application (or repack manually), if you will want to change some values in that config. If you're not really planning to change values after distribution, than usually it's better to pack it in jars and read as a resource.

2. Reading from resources.

Java has a mechanism to read resources from classpath. To do so, you first need to pack resources in your usual jars, that goes to classpath. Then you can load them in your programm by obtaining the appropriate classloader reference. Usually you just use any class in context:

InputStream s = AnyClass.class.getClassLoader().getResourceAsStream("/config.properties");
//or shortcut version
InputStream s = AnyClass.class.getResourceAsStream("/config.properties");

//now can use this input stream as usually, i.e. to load as properties
Properties props = new Properties();
props.load(inputStream);

Now for your question on how to use this resource loading properly with maven. By default maven packs all files in <MODULE_DIR>/src/main/resources into the resulting jar. So all you need is to place your abc.txt into <MODULE_DIR>/src/main/resources/whatever/abc.txt and load it as ...getResourceAsStream("/whaterver/abc.txt"). That will work no matter, how you're running your app: from IDE or after packaging. Than do with it whatever you've done.

Upvotes: 14

Related Questions