简体   繁体   English

如何将Enter键从Java应用程序传递到命令行

[英]How to pass the enter key press to command line from a java application

I am writing a java program which will run some installed tools on a Linux Ubuntu OS, I need to execute two consecutive commands in the same process but with making the first one execute completely and then call the second one. 我正在编写一个Java程序,该程序将在Linux Ubuntu OS上运行一些已安装的工具,我需要在同一过程中执行两个连续的命令,但要使第一个命令完全执行,然后再调用第二个命令。 I have tried using "\\n" to separate the two commands as in the following code, but It didn't work. 我曾尝试使用“ \\ n”将两个命令分开,如下面的代码所示,但这没有用。

public static void main (String args[])
{
    List<String> command = new ArrayList<String>();
    command.add("spin");
    command.add("-p");
    command.add("-u100");
    command.add("D:\\promela\\peterson.pml");
    command.add("\n");
    command.add("cc -o pan pan.c");
    command.add("./pan");


    String[] commandArray = command.toArray(new String[command.size()]);
    ProcessBuilder pb = new ProcessBuilder(commandArray);
    Process process;
    try {

          process = pb.start();

          BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
          BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
          String errline, outline;


          for(String s : command)
           {
             System.out.println(s + " ");
           }

           while ((outline = br.readLine()) != null)
           {
             System.out.println(outline);
           }

           while ((errline = errReader.readLine()) != null)
           {
              System.err.println(errline);
           }


    } catch (IOException e) 
    {
        e.printStackTrace();

    }
}

I don't think it can be done: 我认为无法做到:

  • Either you launch a terminal/console/bash process, in which you can "type" commands, or 您可以启动终端/控制台/ bash进程,在其中可以“键入”命令,或者
  • you launch a specific executable that can't parse those commands and it won't work. 您启动了无法解析这些命令的特定可执行文件,它将无法正常工作。

Wouldn't it be easier to start 2 processes? 启动2个进程会更容易吗?

Side note: you should not read the out and err streams one after the other, you should read them in parallel in separate threads, or, easier, use ProcessBuilder#redirectErrorStream so you only need to read from one stream (out). 旁注:您不应该一个接一个地读取out和err流,您应该在单独的线程中并行读取它们,或者更方便地使用ProcessBuilder#redirectErrorStream因此您只需要从一个流(out)读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM