java中如何执行命令行语句

如题所述

可以使用java.lang.Process和java.lang.Runtime实现,下面展示两个例子,其它用法请查阅资料:

1、执行ping命令:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessTest {
    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            String cmd = "ping 127.0.0.1";
            // æ‰§è¡Œdos命令并获取输出结果
            Process proc = Runtime.getRuntime().exec(cmd);
            br = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK"));

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            proc.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2、打开浏览器并跳转到百度首页:

import java.io.IOException;

public class ProcessTest {
    public static void main(String[] args) {
        try {
            String exeFullPathName = "C:/Program Files/Internet Explorer/IEXPLORE.EXE";
            String message = "www.baidu.com";
            String[] cmd = {exeFullPathName, message};
            Process proc = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
温馨提示:答案为网友推荐,仅供参考
相似回答