1

我试图让我的程序启动 Enchanter 到 SSH 到我的服务器,但似乎无法弄清楚如何进入和输出到stdinandstdout或任何地方。我只是在 Netbeans 中得到一个空白的输出窗口。如何让 Jar 运行并获取输入/输出?

public class openShell {

public void openShell() throws IOException {
        String line; 
        Scanner scan = new Scanner(System.in);  
        ProcessBuilder builder = new ProcessBuilder ("C:\\Program Files\\Java\\lib\\enchanter-beanshell-0.6.jar", "myscript.bsh"); 
        builder.redirectErrorStream(true); 
        Process process = builder.start();  
        OutputStream stdin = process.getOutputStream (); 
        InputStream stderr = process.getErrorStream (); 
        InputStream stdout = process.getInputStream ();  
        BufferedReader reader = new BufferedReader (new InputStreamReader(stdout)); 
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));  


        while (scan.hasNext()) { 
        String input = scan.nextLine(); 
        if (input.trim().equals("exit")) { 
            // Putting 'exit' amongst the echo --EOF--s below doesn't work. 
            writer.write("exit\n"); 
        } else { 
            writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n"); 
        } 
        writer.flush(); 

        line = reader.readLine(); 
        while (line != null && ! line.trim().equals("--EOF--")) { 
            System.out.println ("Stdout: " + line); 
            line = reader.readLine(); 
        } 
        if (line == null) { 
            break; 
        } 
    } 
}
}


private void LaunchButtonActionPerformed(ActionEvent evt) {
   //openShell open = new openShell();     //RUNS BUT NO IN OR OUTPUT

   //BELOW CODE IS FOR TESTING, JUST TRYING TO GET PROCESSBUILDER TO CONNECT 
   // TO MY JAR
   try {
      ProcessBuilder builder = new ProcessBuilder(
         "Java -jar C:\\Program Files\\Java\\lib\\enchanter-beanshell-0.6.jar"); 
      builder.redirectErrorStream(true); 
      Process process = builder.start();
   } catch (IOException ex) {
       Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
   }
}                                            
4

3 回答 3

3

该方法ProcessBuilder.inheritIO将在您的标准输入、标准输出和标准错误中重定向您的命令流。这适用于 Java 7。

于 2013-04-29T12:13:56.840 回答
1
String[] args = {
  "java", 
  "-jar", 
  "C:\\Program Files\\Java\\lib\\enchanter-beanshell-0.6.jar"
};
ProcessBuilder builder = new ProcessBuilder(args);

从分解上述论点开始。然后实施When Runtime.exec() won't的所有建议。

于 2012-05-18T17:38:30.740 回答
0

这些方法将获得您可以读取和写入的流Process.getInputStreamProcess.getOutputStream

于 2012-05-18T17:35:22.830 回答