我知道这已经被问到过,但是,有时人们会碰到其他答案似乎没有帮助。如何在我的Java应用程序中与C控制台应用程序进行交互
我需要启动一个C应用程序,并通过它的几个输入来浏览其菜单,以最终执行我所需要的。最终的输出(结果)被发送到一个文件,但是中间输出(控制台上打印的菜单和子菜单)很适合打印在我的Eclipse控制台上进行调试。
我根据用户Vince posted on his question和后面提到的工作编写了下面的代码,但它似乎没有为我做。
public final class InteractWithExternalApp {
private static PrintWriter printOut;
private static BufferedReader retrieveOutput;
private static Process p;
private EvaluationTests(){} // suppressing the class constructor
public static void Evaluate(String paramToApp) {
try
{
Runtime rt = Runtime.getRuntime() ;
p = rt.exec("C:\\Path\\To\\Desktop\\appName " + paramToApp);
InputStream in = p.getInputStream() ;
OutputStream out = p.getOutputStream();
retrieveOutput = new BufferedReader(new InputStreamReader(in));
printOut = new PrintWriter(out);
// print menu
if((line = retrieveOutput.readLine()) != null) {
System.out.println(line);
}
// send the input choice -> 0
printOut.println("0");
printOut.flush();
// print sub-menu
if((line = retrieveOutput.readLine()) != null) {
System.out.println(line);
}
// send the input choice
printOut.println("A string");
printOut.flush();
// print sub-menu
if((line = retrieveOutput.readLine()) != null) {
System.out.println(line);
}
/*
Repeat this a few more times for all sub-menu options until
the app finally executes what's needed
*/
}catch(Exception exc){
System.out.println("Err " + exc.getMessage());
}
return;
}
而且,作为一个练习,我试图打开Windows命令提示符并发送一个命令,下面给出here的例子。 cmd.exe打开罚款,但然后通过一个echo
命令没有做任何事情。
OutputStream stdin = p.getOutputStream();
InputStream stdout = p.getInputStream();
stdin.write(new String("echo test").getBytes());
stdin.flush();
有人能请一下吗?我哪里错了?
。请使用ProcessBuilder。它更好地处理白色空间。 – Jayan 2014-11-01 05:28:57
@Jayan,你的意思是在'ProcessBuilder pb = new ProcessBuilder(“C:\\ Path \\ To \\ Desktop \\ appName”,“paramToApp”);''和'pb.start()'? 既然你没有正式回答这个问题,我应该猜测这是唯一的问题,其余的将会很好地工作或者只是一个改进? – 2014-11-01 06:38:21
是的。那将是一个开始。 – Jayan 2014-11-01 07:39:40