日期:2014-05-17  浏览次数:20693 次

Runtime类调用Windows系统cmd命令

Runtime类调用Windows系统cmd命令?

例如:

?

public class ShowDate {

? ?

public static void main(String[] args) {

Runtime run=Runtime.getRuntime();

try {

run.exec("cmd /k start d:\\date.bat");

} catch (Exception e) {

e.printStackTrace();

}

}

}

date.bat文件内容:date

?

补充:

Runtime类:是一个与JVM运行时环境有关的类,这个类是Singleton的。
1、Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一一个得到运行时环境的方法。
2、Runtime上其他大部分的方法都是实例方法,也就是说每次进行运行时调用时都要用到getRuntime方法。
3、Runtime中的exit方法是退出当前JVM的方法,估计也是唯一的一个吧,因为我看到System类中的exit实际上也是通过调用Runtime.exit()来退出JVM的,这里说明一下Java对Runtime返回值的一般规则(后边也提到了),0代表正常退出,非0代表异常中止,这只是Java的规则,在各个操作系统中总会发生一些小的混淆。
例如: Process pro = run.exec("javac");
? ? ? ?int exitVal = pro.exitValue() ;
? ? ? ? ? ? ? ??System.out.println("退出的值:"+exitVal);
? ? ? ? ? ? ? 报错:process has not exited

原因:因为exitValue这个方法是不阻塞的,程序在调用这个方法时外部命令并没有返回所以造成了异常的出现,这里是由另外的方法来等待外部命令执行完毕的,就是waitFor方法。因为当你在一个Process上调用waitFor方法时,当前线程是阻塞的,如果外部命令无法执行结束,那么你的线程就会一直阻塞下去,这种意外会影响我们程序的执行。
例如: ? ? ? ? ? ? ? int exitVal = pro.waitFor() ;
System.out.println("退出的值:"+exitVal);
效果:程序也无法执行完成,它没有输出但却一直悬在那里。
原因:因为本地的系统对标准输入和输出所提供的缓冲池有效,所以错误的对标准输出快速的写入和从标准输入快速的读入都有可能造成子进程的锁,甚至死锁。
例如: ? ? ? ? ? ? ? ?InputStream stderr = pro.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("");
int exitVal = pro.waitFor();
System.out.println("Process exitValue: " + exitVal);
结果:有结果。为了处理好外部命令大量输出的情况,你要确保你的程序处理好外部命令所需要的输入或者输出。

?

Sun的doc里其实说明还有其他的用法:
exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.
那个dir就是调用的程序的工作目录,这句其实还是很有用的。
Windows下调用程序
Process proc =Runtime.