/**
 *  Java调用windows的DOS命令
 */
public class RunDocInJava{
    public static void main(String[] args) {
        InputStream ins = null;
        String[] cmd = new String[] { "cmd.exe", "/c", "ipconfig" };  // 命令行
        try {
        //Runtime.exec()用来执行外部程序或命令
           Process process = Runtime.getRuntime().exec(cmd);
           ins = process.getInputStream();  // 获取执行doc命令后的信息
            //将获取的信息尽可能放入缓冲区
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins));   
            String line = null;  
            //读取信息
            //会先读取缓冲区信息,如果信息不完全才会去读取源数据
            while ((line = reader.readLine()) != null) {   
                System.out.println(line); 
            }
            int exitVal = process.waitFor(); //获取程序返回值   成功为“0”
            System.out.println("return Integer:  "+exitVal);
            process.getOutputStream().close();  //程序中如果没有关闭会造成堆栈溢出
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}


执行截图:

wKioL1ZMBuXRsohXAAI5aleHLFA058.jpg

windows 和 linux上面调用的一些区别举例:

Windows下调用程序

Process proc =Runtime.getRuntime().exec("exefile");

Linux下调用程序就要改成下面的格式

Process proc =Runtime.getRuntime().exec("./exefile");

Windows下调用系统命令

String [] cmd={"cmd","/C","copy exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);

Linux下调用系统命令就要改成下面的格式

String [] cmd={"/bin/sh","-c","ln -s exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);

Windows下调用系统命令并弹出命令行窗口

String [] cmd={"cmd","/C","start copy exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);

Linux下调用系统命令并弹出终端窗口就要改成下面的格式

String [] cmd={"/bin/sh","-c","xterm -e ln -s exe1 exe2"};
Process proc =Runtime.getRuntime().exec(cmd);

还有要设置调用程序的工作目录就要

Process proc =Runtime.getRuntime().exec("exeflie",nullnew File("workpath"));

windows和linux调用区别举例参考自:http://robinjoe.iteye.com/blog/1201388