java使用外部程序方法
在java中可以使用Runtime类和ProcessBuilder类两种方式来执行外部程序
ProcessBuilder类
参数少的情况:
//创建processBuilder对象
ProcessBuilder processBuilder = new ProcessBuilder();
//设置第三方应用命令
processBuilder.command("ping", "127.0.0.1");
//将标准输入流和错误流合并
processBuilder.redirectErrorStream(true);
//启动一个进程
Process process = processBuilder.start();
//通过标准输入流拿到正常错误的信息
InputStream inputStream = process.getInputStream();
//转成字符流输出
InputStreamReader reader = new InputStreamReader(inputStream,"GBK");
//缓冲
char[] chars = new char[1024];
int len = -1;
while ((len = reader.read(chars)) != -1){
String string = new String(chars, 0, len);
System.out.println(string);
}
//关流
reader.close();
inputStream.close();
参数多的情况;
//创建processBuilder对象
ProcessBuilder processBuilder = new ProcessBuilder();
//设置第三方应用命令
List<String> list = new ArrayList<>();
list.add("E:\\ffmpeg\\bin\\ffmpeg.exe");
list.add("-i");
list.add("E:\\ffmpegtest\\1.mp4");
list.add("-hls_time");
list.add("10");
list.add("-hls_list_size");
list.add("0");
list.add("-hls_segment_filename");
list.add("E:\\ffmpegtest\\hls\\m3u8_%05d.ts");
list.add("E:\\ffmpegtest\\hls\\1.m3u8");
processBuilder.command(list);
//将标准输入流和错误流合并
processBuilder.redirectErrorStream(true);
//启动一个进程
Process process = processBuilder.start();
//通过标准输入流拿到正常错误的信息
InputStream inputStream = process.getInputStream();
//转成字符流输出
InputStreamReader reader = new InputStreamReader(inputStream,"GBK");
//缓冲
char[] chars = new char[1024];
int len = -1;
while ((len = reader.read(chars)) != -1){
String string = new String(chars, 0, len);
System.out.println(string);
}
//关流
reader.close();
inputStream.close();