【发布时间】:2012-08-14 08:53:05
【问题描述】:
我想验证一些东西,因为在我看来它是有道理的,但在 Java 中,它不起作用。
我正在尝试通过我的应用程序运行另一个 Jar 文件。准确地说,是一个 Minecraft 服务器。我已经掌握了所有基础知识(使用ProcessBuilder、使用参数执行、等待退出代码等),但有一件事我无法弄清楚。向应用程序发送命令。这是我的CommandLineSender 课程的一部分:
public class CommandLineSender extends Thread {
private BufferedWriter output;
private InputStream source; // Set to System.in when creating the object
private boolean stopRequested;
public CommandLineSender(Process sendTo, InputStream source) {
this.output = new BufferedWriter(new OutputStreamWriter(sendTo.getOutputStream()));
this.source = source;
System.out.println("Source InputStream initiated: " + source.toString());
this.stopRequested = false;
}
@Override
public void run() {
System.out.println("Run called.");
Scanner cmdScanner = new Scanner(source);
while (cmdScanner.hasNextLine() && !stopRequested) {
System.out.println("Has next line");
String msg = cmdScanner.nextLine();
write(msg);
System.out.println("Wrote: " + msg);
}
// Close the scanner and BufferedWriter
System.out.println("Closed.");
}
// Other various methods
protected void write(String msg) {
try {
output.write(msg);
} catch (IOException e) {
System.err.println("Unable to write message because of an unhandled IOException: " + e.getMessage());
}
}
我得到的输出是这样的:
(Default Minecraft server output)
help // My command
Has next line
Wrote: help
这可能无关紧要,但我正在使用这些参数执行我的服务器:
java -Xmx1024M -Xms1024M -jar (path to server jar) nogui
感谢您的宝贵时间。
【问题讨论】:
-
发送的命令不起作用?编写命令后尝试刷新输出流(output.flush())。
-
@davidbuzatto 不,应用程序没有响应。
-
在写入所需的命令后尝试刷新流:
output.flush()。 -
我把它放在
output写的地方之后,仍然没有结果。
标签: java command console-application