Yaz Yaz - 5 months ago 23
Bash Question

get Result from shell command on jTextArea

I have to execute a shell commande windows from java swing app and get real time result :

String cmd = jTextField1.getText();

StringBuffer output = new StringBuffer();

Process p;
try {
p = Runtime.getRuntime().exec(cmd);

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";
while ((line = reader.readLine()) != null) {
System.out.println("" + line);
jTextArea1.append(line + "\n");
}

} catch (Exception e) {
e.printStackTrace();
}


the problem is that writing in jTextArea is after execute finish not real time like System.out.println(..) .

Answer

Try creating a Thread and use Thread.sleep() to do the live updating of the JTextArea.

Create a subclass like following

class Work implements Runnable {

        String cmd;

        Work(String c) {
            this.cmd = c;
        }

        @Override
        public void run() {
            Process p;
            try {
                p = Runtime.getRuntime().exec(cmd);

                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

                String line = "";
                while ((line = reader.readLine()) != null) {
                    System.out.println("" + line);
                    Thread.sleep(500);
                    jTextArea1.append(line + "\n");
                }

            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

Change the code as following

String cmd = jTextField1.getText();
StringBuffer output = new StringBuffer();
new Thread(new Work(cmd)).start()