2

我正在尝试编写一个小型 Java 应用程序,它可以让我使用 Java Process/ProcessBuilder API 在屏幕外运行 Bukkit 服务器。

我能够很好地从服务器获取输出,但服务器不响应由Process.getOutputStream()(链接到进程输入流)返回的输出流写入的命令。

我尝试用我自己的测试代码来做这件事,它奏效了。System.in从接收到写入输出流的文本的单独进程读取。

Bukkit 是不听System.in还是怎么的?如果不是,那怎么可能?有任何想法吗?

try {
    ProcessBuilder pb = new ProcessBuilder();
    File dir = new File("C:/Users/Brian/Desktop/MC-Server/Bukkit-Testing");
    pb.directory(dir);
    pb.command(new String[] {"java", "-Xincgc", "-Xmx1G", "-jar", "craftbukkit-1.0.1-R1.jar"});
    pb.redirectErrorStream(true);
    final Process p = pb.start();
    InputStream out = p.getInputStream();
    BufferedReader r1 = new BufferedReader(new InputStreamReader(out));
    String s = null;
    new Thread(new Runnable() {

        @Override
        public void run() {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            Scanner scan = new Scanner(System.in);
            String input = null;
            while((input=scan.nextLine()) != null) {
                if(input.equals("exit")) {
                    p.destroy();
                    break;
                }
                try {
                    bw.write(input);
                    bw.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }).start();
    while((s=r1.readLine()) !=null)
        System.out.println(s);
} catch (IOException e) {
    e.printStackTrace();
}
4

1 回答 1

3

我不认为 Bukkit 使用它System.in,所以我们必须做一个解决方法。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;

import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;

public class ConsolePlugin extends JavaPlugin {

    public Logger log;

    public void onEnable(){
        log = this.getLogger();
        log.info("BufferedReader has been enabled!");
        new Thread(new Runnable(){
            public void run(){
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line = null;
                while (true){
                    try {
                        line=br.readLine();
                    } catch (Exception e) {e.printStackTrace();}
                    if (line!=null){
                        Bukkit.dispatchCommand(Bukkit.getConsoleSender(), line);
                        System.out.println(line);
                    }
                }
            }
        }).start();
    }

    public void onDisable(){
        log.info("BufferedReader has been disabled.");
    }
}

发送命令:

bw.write(input);
bw.nextLine();
bw.flush();
于 2012-07-04T14:52:22.230 回答