Java调用linux系统命令   Leave a comment

Java可以直接调用Linux命令,形式如下:
Runtime.getRuntime().exec(command)
与用java调用windows命令形式类似,并且比windows的写法上稍微简略一些。

举例:java执行Linux的ls命令可以这样:

Java代码 复制代码
  • Runtime.getRuntime().exec(“ls”);
Runtime.getRuntime().exec("ls");

java执行windows的del命令,在del前面要带上“cmd.exe /c”,如下:

Java代码 复制代码
  • Runtime.getRuntime().exec(“cmd.exe /c del 目录”);
Runtime.getRuntime().exec("cmd.exe /c del 目录");

但是这样执行时没有任何输出,原因:
调用Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例,
(注意:Runtime.getRuntime().exec(command)返回的是一个Process类的实例),
该 实例可用于控制进程或取得进程的相关信息. 由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过 Process.getOutputStream(),Process.getInputStream(), Process.getErrorStream() 方法重定向给它的父进程了.用户需要用这些stream来向 子进程输入数据或获取子进程的输出. 可以采用如下方法:

Java代码 复制代码
  • try
  • {
  •  Process process = Runtime.getRuntime().exec (“ls”);
  •  InputStreamReader ir=newInputStreamReader(process.getInputStream());
  •  LineNumberReader input = new LineNumberReader (ir);
  •  String line;
  •  while ((line = input.readLine ()) != null){
  •  System.out.println(line)
  • }
  • catch (java.io.IOException e){
  •  System.err.println (“IOException ” + e.getMessage());
  • }

 

Environment Variables

Many operating systems use environment variables to pass configuration information to applications. Like properties in the Java platform, environment variables are key/value pairs, where both the key and the value are strings. The conventions for setting and using environment variables vary between operating systems, and also between command line interpreters. To learn how to pass environment variables to applications on your system, refer to your system documentation.

Querying Environment Variables

On the Java platform, an application uses System.getEnv to retrieve environment variable values. Without an argument, getEnv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values. This is demonstrated in the EnvMap example:

import java.util.Map;

public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",
                              envName,
                              env.get(envName));
        }
    }
}

With a String argument, getEnv returns the value of the specified variable. If the variable is not defined, getEnv returns null. The Env example uses getEnv this way to query specific environment variables, specified on the command line:

public class Env {
    public static void main (String[] args) {
        for (String env: args) {
            String value = System.getenv(env);
            if (value != null) {
                System.out.format("%s=%s%n",
                                  env, value);
            } else {
                System.out.format("%s is"
                    + " not assigned.%n", env);
            }
        }
    }
}

Passing Environment Variables to New Processes

When a Java application uses a ProcessBuilder object to create a new process, the default set of environment variables passed to the new process is the same set provided to the application’s virtual machine process. The application can change this set usingProcessBuilder.environment.

Platform Dependency Issues

There are many subtle differences between the way environment variables are implemented on different systems. For example, Windows ignores case in environment variable names, while UNIX does not. The way environment variables are used also varies. For example, Windows provides the user name in an environment variable called USERNAME, while UNIX implementations might provide the user name in USERLOGNAME, or both.

To maximize portability, never refer to an environment variable when the same value is available in a system property. For example, if the operating system provides a user name, it will always be available in the system property user.name.

Posted 2010年11月28日 by gw8310 in dos, java, linux

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: