Java执行cmd命令工具类
2024-09-08 09:21:56
工具类:
public class CmdTask implements Runnable {
private String command;
private String dirPath;
public CmdTask(String dirPath, String command) {
this.dirPath = dirPath;
this.command = "cmd.exe /c " + command;;
}
@Override
public void run() {
Process process = null;
int exitVal = 0;
try {
process = Runtime.getRuntime().exec(command, null, new File(dirPath));
// Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
//针对这种情况,我们只需要将子进程的stream重定向出来即可。
new RedirCmdStreamThread(process.getInputStream(), "INFO").start();
new RedirCmdStreamThread(process.getErrorStream(), "ERR").start();
exitVal = process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
if (exitVal != 0) {
throw new RuntimeException("cmd任务执行失败");
}
}
class RedirCmdStreamThread extends Thread {
InputStream is;
String printType;
RedirCmdStreamThread(InputStream is, String printType) {
this.is = is;
this.printType = printType;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(printType + ">" + line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
工具类使用案例:
command = "cmd.exe /c ffmpeg -i video.m4s -i audio.m4s -codec copy " + abPath;
new CmdTask(videoPath,command).run();
最新文章
- php调接口
- 【转载】.NET模拟POST登录并保持登录状态
- 351. Android Unlock Patterns
- hdu 3400 Line belt
- iOS TextField输入限制(限制长度、只能输入数字,只能输入数字字母……)
- jdbc hibernate myBatis比较
- Effective Java 第三版——7. 消除过期的对象引用
- 1.关于QT中的Graphics绘图,定时器,动画,将窗口中的内容打印到图片上,打印机,打印预览
- FineUIPro/Mvc/Core v5.4.0即将发布(Core基础版,新功能列表)!
- STM32时钟
- vue入门练习(一)
- mysql表名作为参数传入存储过程
- 前端入门6-JavaScript客户端api&;jQuery
- nginx 负载均衡5种配置方式
- Spring Batch 背景
- 漂亮的CSS3提交意见输入框样式
- OAF 交互式列车 上一步 下一步的简单使用
- 【我的Android进阶之旅】解决Android Studio 运行gradle命令时报错: 错误: 编码GBK的不可映射字符
- centos上Jenkins搭建
- php执行多个存储过程(二)