IT评测·应用市场-qidao123.com
标题:
java调用本机的命令 如ping、打开文本等
[打印本页]
作者:
道家人
时间:
2023-4-6 20:52
标题:
java调用本机的命令 如ping、打开文本等
最近接触到用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();
}
}
}
复制代码
执行结果:就是指定的文件打开了
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4