简体   繁体   中英

System.getenv is not supported in Java 1.4. What is the alternative way?

I want to find the value of a particular env variable $ABC in Java code.
Since System.getenv("ABC"); is not an option on Java 1.4 what is the alternative for it?

Commentators of your question are 100% right. If it is possible in any way then upgrade your Java version. If it is not possible to upgrade and if your target environment is known to you, then you can for example execute a bash command and read the result. Something like this:

p = Runtime.getRuntime().exec("echo $" + yourEnvVariable);
p.waitFor();

BufferedReader reader =
     new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";
while ((line = reader.readLine())!= null) {
  sb.append(line + "\n");
}
String variableValue = sb.toString();

But this is in no way a good practice since it is very dependent of operating system where the program is executed.

PS I have not tested if it actually works since I have nowhere to run Java 1.4.

A better idea is to create a wrapper script to launch your program, and have it put the values of specific environment variables into the JVM's system Properties object using -Dname=value parameters.

Obviously you would need to implement different wrappers for each OS family.


And, seriously, you should not be continuing to develop for / on Java 1.4. You are missing ~15 YEARS of security patches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM