infoSyStem
infoSyStem

Reputation: 145

how to create environmental variables for my program

I made a program in Java that uses two external databases. The paths to these databases are hard-coded inside my program code.

In order to make this program usable for other users on other computers (who should also install these two databases on their computers), I think that the path for these two databases should be added as environmental variables ? How could this be done ?

I am not a professional when it comes to environmental variables, so can you please advise what should be done in this case?

Thanks in advance

Upvotes: 0

Views: 1627

Answers (3)

chooban
chooban

Reputation: 9256

Rather than environment variables, a properties file would be useful and more portable. For example, in your properties file you could have the following:

db.url = jdbc://foo/bar?whatever
db.user = username
db.password = password

Then your code could read that in using the follow:

Properties properties = new Properties();
try {
  properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
  System.err.println( "Eeeek!" );
}

System.out.println( properties.getProperty( "db.url" ) );

Handily, properties objects allow you to specify defaults, so you could still have the hardcoded values if you want and then override them with the external file.

Upvotes: 0

Java42
Java42

Reputation: 7706

Environment vars are usually not be the best way to handle app config, but if you must, the specific OS docs are needed to learn how to set them and from Java use:

Map map = System.getenv();

Upvotes: 0

ruakh
ruakh

Reputation: 183211

To get the value of an environment variable in Java, you write something like this:

String pathToDatabase = System.getenv().get("PATH_TO_DATABASE");

(where PATH_TO_DATABASE is the name of the environment variable). This uses System.getenv() to get a map of all environment variables.

To set the value of an environment variable in Linux, your users can write something like this:

export PATH_TO_DATABASE=/this/is/the/path/to/the/database

before running the program.

Upvotes: 1

Related Questions