Get the environment variable of the operating system in Java
Source: Internet
Author: User
Note: This is to get the environment variables of the operating system instead of JVM-related variables (see my previous blog: Get environment variables in Java ).
It may be to create an atmosphere where the JVM is the operating system platform, or to emphasize the independence of the Java platform. I do not know when Java has discarded the system. getenv (string) function. Therefore, Java can only obtain some of its own Defined variables, but cannot interact with the environment variables of the operating system, you can only set the variables to be passed to Java when running the "-d" parameter.
Therefore, the only way is to judge the operating system first, and then use the operating system command to call up the list of environment variables and try to get the output list. The following is an example from http://www.rgagnon.com/javadetails/java-0150.html: Import java. Io.*;
Import java. util.*;
PublicClassReadenv{ PublicStaticProperties getenvvars () throws throwable{
PROCESS p=Null;
Properties envvars=NewProperties ();
Runtime R=Runtime. getruntime ();
String OS=System. getproperty ("OS. Name"). Tolowercase (); //System. Out. println (OS ); If(OS. indexof ("Windows 9")>-1){
P=R.exe C ("Command.com/C set");
} ElseIf(OS. indexof ("NT")>-1) |(OS. indexof ("Windows 20")>-1) |(OS. indexof ("Windows XP")>-1)){ //Thanks to juanfran for the XP fix! P=R.exe C ("Cmd.exe/C set");
} Else{ //Our last hope, we assume Unix (thanks to H. Ware For the fix) P=R.exe C ("Env");
}
Bufferedreader br=NewBufferedreader
(NewInputstreamreader (P. getinputstream ()));
String line; While(Line=BR. Readline ())! =Null){ IntIdx=Line. indexof ('=');
String key=Line. substring (0, Idx );
String Value=Line. substring (idx+1);
Envvars. setproperty (Key, value ); //System. Out. println (Key + "=" + value ); } ReturnEnvvars;
}
PublicStaticVoidMain (string ARGs []){ Try{
Properties P=Readenv. getenvvars ();
System.Out. Println ("The current value of temp is:"+
P. getproperty ("Temp"));
} Catch(Throwable E){
E. printstacktrace ();
}
}
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service