runtime.exec()花费无限的时间来执行代码

我想执行一个带有2个参数的命令。 1.输入文件名2.output文件名。

命令是sixV1.1 outputFile.txt代码是:

String cmd= "sixV1.1 outputFile.txt"; Process p=Runtime.getRuntime().exec(cmd); int retValue=p.waitFor(); 

当我运行上面的代码时,它将花费无限的时间。 是否有可能在cmd中给出字符。请建议我….

在Java中启动进程时,进行输入/输出重定向的正确方法是从进程的流中写入/读取:

 Process p = Runtime.getRuntime().exec("sixV1.1"); InputStream is = p.getInputStream(); // read from is and write to outputFile.txt OutputStream os = p.getOutputStream(); // read from inputFile.txt and write to os 

Michael C. Daconta撰写了一篇关于使用Java运行时成功命令行调用的精彩博客文章 。 它并不像你想象的那么容易!

该博客文章中的以下代码摘录描述了“MediocreExecJava”,这是一个使用Runtime.exec()成功运行程序并在不挂起的情况下管理其输入和输出的类。 我之前使用它并且它有效。 我强烈推荐阅读post以了解原因!

 import java.util.*; import java.io.*; public class MediocreExecJavac { public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("javac"); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line = null; System.out.println(""); while ( (line = br.readLine()) != null) System.out.println(line); System.out.println(""); int exitVal = proc.waitFor(); System.out.println("Process exitValue: " + exitVal); } catch (Throwable t) { t.printStackTrace(); } } }