简体   繁体   中英

Give input command and Get Command Prompt complete Output to textarea In Java

I am unable to read the complete output of the program and sometimes it hangs the interface and does not compiles completely. In the output console of the netbeans it displays complete output but not in jtextarea.

Help me out to first execute command in cmd(command prompt) and then read output to textarea from cmd.

In cmd the command executes quickly with complete results. But I have no idea how to get results from cmd.

Here is my code:

String line;
String [] cmds={"xyz.exe","--version"};
try{
 Process p =Runtime.getRuntime().exec(cmds);                   
     p.waitFor();
     int val=p.exitValue();
     if(val==0)
     {
         b1.setForeground(Color.green);                              
         InputStream ins = p.getInputStream();
         InputStreamReader insr = new InputStreamReader(ins);
         BufferedReader br = new BufferedReader(insr);
         while ((line = br.readLine()) != null) {
           System.out.println( line);
           t1.setText( line);
         } 
     } else if(val==1)
     {
         b1.setForeground(Color.red);
         InputStream error = p.getErrorStream();
         InputStreamReader isrerror = new InputStreamReader(error);
         BufferedReader bre = new BufferedReader(isrerror);
         while ((line = bre.readLine()) != null) {
           t1.setText(line);

         }
     }
    } catch(IOException e){
        System.out.println("error");
        e.printStackTrace();
      } catch (InterruptedException ex) {
          Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

The problem I see is this. You are trying to execute a program but you are not reading from the outputstream (ie. getInputStream() of Process) of the program until it has finished executing. So if your subProcess happens to have a lot of output and it exhausts the buffers, then the subProcess will be blocked.

So to solve your problem, you need to be absolutely reading the inputstream and errorstream while the subprocess is still executing to avoid the subprocess being blocked. You can either use blocking IO which means you need separate threads to service outputstream and errorstream or non blocking IO which you can use 1 thread that continually monitor outputstream & errorstream for data to be read.

Java Docs on java.lang.Process says

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

import java.io.*;
import java.nio.channels.*;
import java.nio.*;

public static void nioExecute() throws Exception {
    Process p = Runtime.getRuntime().exec("javac");
    ReadableByteChannel stdoutChannel = Channels.newChannel(p.getInputStream());
    ReadableByteChannel stderrChannel = Channels.newChannel(p.getErrorStream());
    ByteBuffer buffer = ByteBuffer.allocate(1000);

    StringBuilder stdOut = new StringBuilder();
    StringBuilder stdErr = new StringBuilder();

    while(stdoutChannel.isOpen() || stderrChannel.isOpen()) {
        buffer.clear();
        if(stderrChannel.isOpen()) {
            int bytesRead = stderrChannel.read(buffer);
            if(bytesRead>0) stdErr.append(new String(buffer.array(),0,bytesRead));
            if(bytesRead==-1) stderrChannel.close();
        }
        buffer.clear();
        if(stdoutChannel.isOpen()) {
            int bytesRead = stdoutChannel.read(buffer);
            if(bytesRead>0) stdOut.append(new String(buffer.array(),0,bytesRead));
            if(bytesRead==-1) stdoutChannel.close();
        }
        Thread.sleep(100);
    }

    if(stdOut.length()>0) System.out.println("STDOUT: " + stdOut);
    if(stdErr.length()>0) System.out.println("STDERR: " + stdErr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM