如果你想在 JAVA 中执行其他操作系统的程序,例如:运行 DOS 命令、shell 脚本、exe 文件,只需了解 java.lang.Process 类的用法,上述问题皆可实现。
1.输入
以 Windows 平台为例,来看一个简单的例子:
ProcessBuilder 可用于构建 Process ,其构造方法接收 String 类型的可变参数,如果命令带有多个参数,需分割成多个 String 字符串 ;
getInputStream() 获取进程标准的输出流,再使用 InputStreamReader 读取其中的字符,如果包含中文字符,需要指定编码格式;
BufferedReader 开启缓冲输入,增加读取速度;
public class ProcessDemo {
public static void command(String command) throws IOException {
Process process = new ProcessBuilder(command.split(" ")).start();
//指定编码格式,解决中文乱码问题
BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
String s;
while ((s = results.readLine()) != null) {
System.out.println(s);
}
//关闭流
results.close();
//销毁进程
process.destroy();
}
public static void main(String[] args) throws IOException {
command("ping www.baidu.com");
}
}
正在 Ping www.a.shifen.com [14.215.177.39] 具有 32 字节的数据:
来自 14.215.177.39 的回复: 字节=32 时间=16ms TTL=55
来自 14.215.177.39 的回复: 字节=32 时间=16ms TTL=55
来自 14.215.177.39 的回复: 字节=32 时间=16ms TTL=55
来自 14.215.177.39 的回复: 字节=32 时间=16ms TTL=55
14.215.177.39 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 16ms,最长 = 16ms,平均 = 16ms
2.输出
假设我们现在需要往进程中输出信息,则需要使用 getOutputStream() 获取面向进程的输出流;
需要注意的是,写入完成后必须得执行 flush() 和 close() 方法,否则进程无法判断写入是否完成,导致写入失败;
- 示例
public class ProcessDemo {
public static void command(String command) throws IOException, InterruptedException {
Process process = new ProcessBuilder(command.split(" ")).start();
OutputStream outputStream = process.getOutputStream();
String str="2021/12/01";
outputStream.write(str.getBytes());
outputStream.flush();
//关闭输出流
outputStream.close();
//指定编码格式,解决中文乱码问题
BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
String s;
while ((s = results.readLine()) != null) {
System.out.println(s);
}
//关闭输入流
results.close();
//销毁进程
process.destroy();
}
public static void main(String[] args) throws IOException, InterruptedException {
command("CMD /C date");
}
}
当前日期: 2021/12/08 周三
输入新日期: (年月日) 2021/12/01
本次分享至此结束,希望本文对你有所帮助,若能点亮下方的点赞按钮,在下感激不尽,谢谢您的【精神支持】。
若有任何疑问,也欢迎与我交流,若存在不足之处,也欢迎各位指正!