我试图将输入转发给流程。它是一个Minecraft服务器,所以我需要向它发送命令。我尝试这种方式,但它没有发送任何东西。 (我还检查了日志文件)
public static void main(String[] args) throws IOException {
File file = new File("spigot.jar");
if(file.exists()) {
ProcessBuilder builder = new ProcessBuilder("java", "-jar", "spigot.jar");
Process p = builder.start();
new Thread(() -> {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = "";
try {
while((s = br.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
new Thread(()-> {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String cmd = "";
try {
while((cmd = input.readLine()) != null) {
bw.write(cmd);
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
while(true) {
if(!p.isAlive()) {
System.out.println("Server closed.");
System.exit(0);
}
}
}).start();
} else {
System.out.println("spigot.jar not found.");
System.exit(0);
}
}
编辑: 我使用线程重写了代码,但我遇到了同样的问题
答案 0 :(得分:0)
解决。
我需要添加" bw.newline()"发送ENTER,并使服务器执行我的命令