简体   繁体   English

输入命令并获取命令提示符完整输出到Java中的textarea

[英]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. 在netbeans的输出控制台中,它显示完整的输出,但不在jtextarea中显示。

Help me out to first execute command in cmd(command prompt) and then read output to textarea from cmd. 帮助我先在cmd(命令提示符)中执行命令,然后从cmd读取输出到textarea。

In cmd the command executes quickly with complete results. 在cmd中,该命令可以快速执行并获得完整结果。 But I have no idea how to get results from cmd. 但是我不知道如何从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. 您正在尝试执行一个程序,但是直到完成执行之后,您才从该程序的输出流(即Process的getInputStream())中进行读取。 So if your subProcess happens to have a lot of output and it exhausts the buffers, then the subProcess will be blocked. 因此,如果您的subProcess恰好有很多输出并且耗尽了缓冲区,那么subProcess将被阻塞。

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. 您可以使用阻塞IO(这意味着您需要单独的线程来服务输出流和错误流),也可以使用非阻塞IO(可以使用1个线程来连续监视输出流和错误流以读取数据)。

Java Docs on java.lang.Process says java.lang.Process上的Java文档说

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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