0

我需要通过java访问节点上的控制台如何做到这一点?

public class Comando {

public static void main(String[] args) {
    String comando = "C:\\Program Files\\nodejs\\node.exe";  
    try {  
       Process process = Runtime.getRuntime().exec(comando);   
       OutputStream stdin = process.getOutputStream ();
       InputStream stderr = process.getErrorStream ();
       InputStream stdout = process.getInputStream ();


       stdin.write("1+2".getBytes());
       stdin.flush();
    //   System.out.print(stdout.read());
       stdin.close();
       System.out.print(stdout.read());

       //BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));
       //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

      // writer.close();

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

2 回答 2

0

我希望这node.exe需要文本,而不是您使用的二进制文件。

这意味着使用 PrintWriter 写入文本行并使用 BufferedReader 读取文本行会更有意义。

Java 有一个内置的 Javascript 解释器。我假设您由于某种原因不能使用它。

于 2013-09-02T14:22:58.703 回答
0
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

public class Comando {

    public static void main(String[] args) {

        String comando = "C:\\Program Files\\nodejs\\node.exe";
        try {

            ProcessBuilder builder = new ProcessBuilder(comando);
            Process process = builder.start();
            OutputStream stdin = process.getOutputStream();
            InputStream stderr = process.getErrorStream();
            InputStream stdout = process.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    stdout));
            PrintWriter writer = new PrintWriter(stdin);

            writer.write("1+2");
            writer.flush();
            stdin.close();
            System.out.print(reader.read());// return -1

            // writer.close();

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

}

当我尝试读取您的输出时,它继续在我返回-1

于 2013-09-03T11:43:59.527 回答