Java Process Console输出

时间:2018-05-08 16:38:59

标签: java io console streamwriter

我需要有关流程输出的帮助。

我在Process控制台上工作,如果我写入流程输出,我需要关闭写入。如果我想发送另一个命令,我会得到" Stream关闭"错误。任何人都可以帮助我吗?

来源:

public void runServer(String servername) throws InterruptedException{
    try { 
        //ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "start && cmd.exe && cd \""+cm.getDataPath("server")+"\\"+servername+"\\\" && java -jar \""+cm.getDataPath("main")+"\\serverfiles\\"+getServerFile(servername)+"\"");
        ProcessBuilder builder = new ProcessBuilder("cmd", "/c", ""+cm.getDataPath("main")+"\\run.bat "+cm.getDataPath("server")+"\\"+servername+"\\ "+cm.getDataPath("main")+"\\serverfiles\\"+getServerFile(servername)+"\"");
        final Process process = builder.start(); /*Runtime.getRuntime().exec("cmd.exe /c START "+cm.getDataPath("main")+"\\run.bat "+cm.getDataPath("server")+"\\"+servername+"\\ "+cm.getDataPath("main")+"\\serverfiles\\"+getServerFile(servername)+"\"");*/
        final Thread ioThread = new Thread() {
            @Override
            public void run() {
                try {
                    writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
                    final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(process.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        w.printConsole(line+"\n");
                    }
                    reader.close();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            }
        };
        ioThread.start();
        //process.waitFor();
        runningserver = process;
    } catch (IOException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void sendCommand(String command){
    writer = new BufferedWriter(new OutputStreamWriter(runningserver.getOutputStream()));
    try {
        writer.append(command);
        writer.flush();
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

1 个答案:

答案 0 :(得分:0)

每次拨打sendCommand(...)时,都会通过writer.close();关闭服务器的OutputStream周围的BufferedWriter,这也关闭流。不要这样做,因为这会阻止您再次使用此相同的流。实际上,你的sendCommand方法应该重用一个writer字段,你的代码应该只在完成流的时候才关闭writer。