The System.Getenv () method can easily access the environment variable of the platform, but will be abandoned from the beginning, because the method violates the principle of "writing once, run everywhere". In Tiger versions, this method can be used.
Access platform proprietary information is not an easy task. Although the runtime.exec () can be created using Runtime.exec (), the construction parameter set is often a headache because of the difference between the platform. TiGer provides a new ProcessBuilder class that makes access to platform proprietary information easier.
1. Access environment variables
System.Getenv () has two methods:
(1) Specify the environment variable name to obtain environmental variables, as follows:
Public class envtest {
Public static void main (String [] args) {
System.out.println (System.Getenv ("java_home");
}
}
The result of the output may be:
E: /Develop/j2sdk1.4.2_05
(2) Returns the MAP object of all environment variables, the following example outputs all environment variable names and values:
PUBLIC CLASS Envdump {
Public static void main (String [] args) {
For (entry entry: system.getenv (). entryset ()) {
System.out.println (entry.getKey () "=" entry.getValue ());
}
}
}
2, ProcessBuilder
l Early Java version allows the Runtime.exec () method to create a native process, which is still valid, but because the String array is used as a parameter, the File parameter is used as the working directory, so the subsystem is difficult
l Use the new ProcessBuilder class to simplify this process
l Here is a simple example of starting Editplus:
Public class processtest {
Public static void main (string [] args) throws oException {
Process P = New ProcessBuilder ("C: // Program Files // EditPlus 2 // Editplus.exe"). Start ();
}
}
l The following is an example of specifying the parameters when the command is executed:
Public class processtest {
Public static void main (string [] args) throws oException {
Process P = New ProcessBuilder ("ping", "sina.com.cn"). Start ();
InputStream IS = p.getinputStream ();
BufferedReader Br = New BufferedReader (NEW InputStreamReader (IS));
String line;
WHILE ((line = br.readline ())! = null) {
System.out.println (line);
}
}
}
l ProcessBuilder provides a Directory () method changes the working directory of the process, using the Environment () method to add and delete environment variables in the process space, below is from JDK5:
ProcessBuilder PB = New ProcessBuilder ("MyCommand", "Myarg1", "Myarg2");
Map
Env.put ("var1", "myvalue");
Env.remove ("Othervar");
Env.put ("var2", env.get ("var1") "suffix");
Pb.directory ("mydir");
Process p = pb.Start ();