我需要通过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();
}
}
}
答案 0 :(得分:0)
我希望node.exe
需要文本,而不是二进制文件。
这意味着使用PrintWriter编写文本行和BufferedReader来读取文本行会更有意义。
Java有一个内置的Javascript解释器。我认为你出于某种原因不能使用它。
答案 1 :(得分: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