2016-01-26 85 views
1

我想开始一个cmd命令,然后在第一个命令完成后,我想运行一个代码来调整一个文件中的一些文字,然后在执行其他命令分开相同的cmd窗口。我不知道如何做到这一点,无论在哪里,我看到的答案都是命令之后的命令,而不是这种情况。编辑文本的代码工作正常,但不启动cmd,但如果我执行cmd命令,它不会更改。代码如下。运行多个CMD命令,通过Java通过一些其他代码

public static void main(String[] args)throws IOException 
    { 
     try 
     { 

      Main m1 = new Main(); 



      Process p= Runtime.getRuntime().exec("cmd /c start C:/TERRIERS/terrier/bin/trec_setup.bat"); 
      p.waitFor(); 

/*code to change the text*/ 

      m1.answerFile(1); 
      m1.questionFile(1); 

/**********************/ 
//code to add another command here (SAME WINDOW!) 

/************************/ 



     } 



     catch(IOException ex){ 

     } 

     catch(InterruptedException ex){ 

     } 

回答

3

执行cmd,并发送你的命令行(蝙蝠)标准输入。

Process p = Runtime.getRuntime().exec("cmd"); 
    new Thread(() -> { 
     try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) { 
      String line; 
      while ((line = reader.readLine()) != null) 
       System.out.println(line); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    }).start(); 
    try (PrintStream out = new PrintStream(p.getOutputStream())) { 
     out.println("C:/TERRIERS/terrier/bin/trec_setup.bat"); 
     out.println("another.bat"); 
     // ..... 
    } 
    p.waitFor(); 
2

对于初学者来说,\C选项执行初始命令之后终止CMD。改为使用\K

您将无法使用waitFor()来检测初始命令何时完成,因为如果您等到CMD终止,您将无法重新使用相同的进程。

相反,你需要阅读CMD过程的输出,以检测该批处理文件是完整的,系统提示您输入另一个命令时。然后写要执行虽然Process的输入流中的下一个命令行。

听起来像一个痛苦。为什么你需要使用同一个窗口?