Naveen Dhalaria
Naveen Dhalaria

Reputation: 153

How to read folder path dynamically?

Let's say I have path like

"jboss/server/Default/deploy/Product_071016.ear/Product_071016.war/web-inf/classes/"

I want to read this path using java and create a new file inside classes folder. Hard-Coding is not an option and it needs to be adaptable.

In this path Product_071016.ear and Product_071016.war names changes(i.e. date,month,year is appended after "_"). How can I do this?

Upvotes: 0

Views: 1644

Answers (1)

STaefi
STaefi

Reputation: 4377

Depend on your requirements, you can have some options, such as:

  1. Have a config file, for example: paths.properties

    which contains every dynamically changing path as a key/value pair in each line. You can find out about the format of .properties files here. The key is a CONSTANT name. Every time the path changes, somebody should change the value assign to this constant key in the paths.properties. Since you can load this config file using a Properties object in java, you can have the changed path by giving it's CONSTANT key to the Properties object. Properties is somehow a customized Map for dealing with .properties files.

    The contents of your paths.properties can be like this:

     PATH_TO_CLASSES_FOLDER=jboss/server/Default/deploy/Product_071016.ear/Product_071016.war/web-inf/classes/
    

    So after you loaded the key/values from .properties file using Properties object, by giving the key PATH_TO_CLASSES_FOLDER you get the desired path which is stored in the file.

  2. You can set an System Variable in every Operating System, and then you can read it's value in java using the following line of code:

    String pathToClassesFolder = System.getenv("PATH_TO_CLASSES");
    

Using either ways, you didn't hard-code any dynamic path in your code and the requirement is achieved. Even if you don't want to hard-code the path of the config file, you can combine both ways:

  1. Define the path of config file as a System Variable

  2. Read the path to config file, then load it by Properties object and use the PATH_TO_CLASSES_FOLDER key to get the classes folder path.

Good Luck.

Upvotes: 1

Related Questions