如何在Java的jtextarea上显示shell命令输出?

问题描述 投票:2回答:4

如何在Java的jtextarea上显示shell命令输出?

请帮助谢谢

java swing
4个回答
2
投票

您可以在代码段下方获得shell命令输出,在while循环上设置jtextarea。

    try {
        String cmd = "java";  // Set shell command
        Process child = Runtime.getRuntime().exec(cmd);

        InputStream lsOut = child.getInputStream();
        InputStreamReader r = new InputStreamReader(lsOut);
        BufferedReader in = new BufferedReader(r);

        // read the child process' output
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
            // You should set JtextArea
        }
    } catch (Exception e) { // exception thrown

        System.err.println("Command failed!");

    }

2
投票

您需要将标准输出读取为流程输入流,并使用来自另一个线程的事件队列来更新JTextArea。请参见下面的示例代码:

public class OutputDisplayer implements Runnable {

protected final JTextArea textArea_;
protected Reader reader_ = null;

public OutputDisplayer(JTextArea textArea) {
    textArea_ = textArea;
}

public void commence(Process proc) {
    InputStream in = proc.getInputStream();
    reader_ = new InputStreamReader(in);
    Thread thread = new Thread(this);
    thread.start();
}

public void run() {
    StringBuilder buf = new StringBuilder();
    try {
        while( reader_ != null ) {
            int c = reader_.read();
            if( c==-1 ) return;

            buf.append((char) c);
            setText( buf.toString() );
        }
    } catch ( IOException ioe ) {
        buf.append("\n\nERROR:\n"+ioe.toString());
        setText( buf.toString() );
    } finally {
        try {
            reader_.close();
        } catch ( IOException ioe ) {
            ioe.printStackTrace();
        }
    }
}


private void setText(final String text) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            textArea_.setText(text);
        }
    });
}
}   

2
投票

除了上面我的评论中的两个链接之外,我还创建并使用了TextAreaOutputStream,它有助于将输出流数据重定向到textarea:

import java.io.IOException;
import java.io.OutputStream;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaOutputStream extends OutputStream {

   private final JTextArea textArea;
   private final StringBuilder sb = new StringBuilder();
   private String title;

   public TextAreaOutputStream(final JTextArea textArea, String title) {
      this.textArea = textArea;
      this.title = title;
      sb.append(title + "> ");
   }

   @Override
   public void flush() {
   }

   @Override
   public void close() {
   }

   @Override
   public void write(int b) throws IOException {

      if (b == '\r')
         return;

      if (b == '\n') {
         final String text = sb.toString() + "\n";
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
               textArea.append(text);
            }
         });
         sb.setLength(0);
         sb.append(title + "> ");
      }

      sb.append((char) b);
   }
}

0
投票
import java.io.OutputStream;

import javax.swing.JTextArea;



/**
 * This class extends from OutputStream to redirect output to a JTextArrea
 * @author www.codejava.net
 *
 */
public class CustomOutputStream extends OutputStream {
    private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char)b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }
} 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package guiconsoleoutput;

/**
 *
 * @author root
 */
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;

public class TextAreaLogProgram extends JFrame {

    /**
     * The text area which is used for displaying logging information.
     */
    private JTextArea textArea;

    private JButton buttonStart = new JButton("Start");
    private JButton buttonClear = new JButton("Clear");

    private PrintStream standardOut;

    public TextAreaLogProgram() {
        super(" CONSOLE ");

        textArea = new JTextArea(50, 10);
        textArea.setEditable(false);
        PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));

        // keeps reference of standard output stream
        standardOut = System.out;

        // re-assigns standard output stream and error output stream
        System.setOut(printStream);
        System.setErr(printStream);

        // creates the GUI
        setLayout(new GridBagLayout());
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.insets = new Insets(10, 10, 10, 10);
        constraints.anchor = GridBagConstraints.WEST;

        add(buttonStart, constraints);

        constraints.gridx = 1;
        add(buttonClear, constraints);

        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.gridwidth = 2;
        constraints.fill = GridBagConstraints.BOTH;
        constraints.weightx = 1.0;
        constraints.weighty = 1.0;

        add(new JScrollPane(textArea), constraints);

        // adds event handler for button Start
        buttonStart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                printLog();
            }
        });

        // adds event handler for button Clear
        buttonClear.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                // clears the text area
                try {
                    textArea.getDocument().remove(0,
                            textArea.getDocument().getLength());
                    standardOut.println("Text area cleared");
                } catch (BadLocationException ex) {
                    ex.printStackTrace();
                }
            }
        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(480, 320);
        setLocationRelativeTo(null);    // centers on screen
    }

    /**
     * Prints log statements for testing in a thread
     */
    private void printLog() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                System.out.println("Time now is " + (new Date()));
                System.out.println("lol ");
                String s = null;

                /*try {

        // run the Unix "ps -ef" command
            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("dir");

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

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command
            System.out.println("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

            // read any errors from the attempted command
            System.out.println("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }

            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("exception happened - here's what I know: ");
            e.printStackTrace();
            System.exit(-1);
        }*/
                try {
                    String cmd = "cmd /c ping 8.8.8.8";  // Set shell command
                    Process child = Runtime.getRuntime().exec(cmd);

                    InputStream lsOut = child.getInputStream();
                    InputStreamReader r = new InputStreamReader(lsOut);
                    BufferedReader in = new BufferedReader(r);

                    // read the child process' output
                    String line;
                    while ((line = in.readLine()) != null) {
                        System.out.println(line);
                        // You should set JtextArea
                    }
                } catch (Exception e) { // exception thrown

                    System.err.println("Command failed!");

                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }

            }
        });
        thread.start();
    }

    /**
     * Runs the program
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TextAreaLogProgram().setVisible(true);
            }
        });

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.