java调用本机的命令 如ping、打开文本等

发布时间 2023-04-06 19:26:52作者: 万笑佛

最近接触到用java代码调用主机的命令部分感觉有点意思整理总结一下

环境jdk1.8  操作系统win10,不用引入其他的包jdk自带的api就可以

一、java调用ping命令

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

//调用本机ping命令
public class ExecPingDemo {
    public static void main(String[] args) {
        try {
            Process p = Runtime.getRuntime().exec("ping www.baidu.com");
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream(),  Charset.forName("GBK")));
            String line;
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

执行结果:
正在 Ping www.a.shifen.com [220.181.38.149] 具有 32 字节的数据:
来自 220.181.38.149 的回复: 字节=32 时间=55ms TTL=48
来自 220.181.38.149 的回复: 字节=32 时间=55ms TTL=48
来自 220.181.38.149 的回复: 字节=32 时间=55ms TTL=48
来自 220.181.38.149 的回复: 字节=32 时间=54ms TTL=48

 

二、java调用打开本机的文件

 

import java.io.IOException;

//打开文件
public class ExecDemoOpen {
    public static void main(String[] args) {
        try {
            String file = "D:/流程描述.txt"; // 文件路径
            Process p = Runtime.getRuntime().exec("cmd /c start " + file); // 执行打开文件的命令行
            p.waitFor(); // 等待程序执行完毕
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 
执行结果:就是指定的文件打开了