-2

I need help with process outputs.

I working on a Process console, and if I write to process output, I need to close to write. If I want to send another command, I get "Stream closed" error. Can anyone help me?

Sources:

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);
    }
}
Akila
  • 1,258
  • 2
  • 16
  • 25
S3nS3IW00
  • 31
  • 6

1 Answers1

0

Every time you call sendCommand(...) you close a BufferedWriter that is wrapped around your server's OutputStream via writer.close();, and this also closes the stream. Don't do this as this prevents you from using this same stream again. In fact, your sendCommand method should re-use a writer field and your code should only close the writer when totally done with the stream.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373