RuntimeDemo

Aus Byte-Welt Wiki
Zur Navigation springenZur Suche springen

Die Klasse java.lang.Runtime besitzt die statische Methode getRuntime(), die das Java Runtime Environment zurückgibt. Mit dieser Referenz können wir externe Programme ausführen, indem wir die exec() Methode der Klasse Runtime aufrufen. <code=java>/*

* RuntimeDemo.java
* The class java.lang.Runtime features a static method called getRuntime(), 
* which retrieves the current Java Runtime Environment. 
* With that reference, we can run external programs by invoking the Runtime class's exec() method.
*
*/

import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*;

public class RuntimeDemo extends JFrame {

   private JButton btRun;
   private JLabel lbCommand;
   private JTextArea textarea;
   private JTextField tfCommand;
   private JToolBar toolbar;
   public RuntimeDemo() {
       super("RuntimeDemo");
       setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
       toolbar = new JToolBar();
       lbCommand = new JLabel("Command: ");
       tfCommand = new JTextField();
       btRun = new JButton("Run");
       textarea = new JTextArea();
       toolbar.setRollover(true);
       toolbar.add(lbCommand);
       toolbar.add(tfCommand);
       btRun.setFocusable(false);
       btRun.addActionListener(new ActionListener() {
           public void actionPerformed(final ActionEvent evt) {
               btRunActionPerformed(evt);
           }
       });
       toolbar.add(btRun);
       getContentPane().add(toolbar, BorderLayout.PAGE_START);
       getContentPane().add(new JScrollPane(textarea), BorderLayout.CENTER);
       setSize(800, 600);
       setLocationRelativeTo(null);
   }
   private void btRunActionPerformed(final ActionEvent evt) {
       btRun.setEnabled(false);
       final String command = tfCommand.getText();
       SwingWorker worker = new SwingWorker() {
           @Override
           protected Object doInBackground() throws Exception {
               runCommand(command);
               return null;
           }
           @Override
           protected void done() {
               JOptionPane.showMessageDialog(RuntimeDemo.this.btRun, "Done");
               btRun.setEnabled(true);
           }
       };
       worker.execute();
   }
   private int runCommand(final String command) {
       int exitVal = -1;
       try {
           String osName = System.getProperty("os.name");
           String[] cmd = new String[3];
           System.out.println(osName);
           if (osName.equals("Windows XP") || osName.equals("Windows NT")) {
               cmd[0] = "cmd.exe";
               cmd[1] = "/C";
               cmd[2] = "\"" + command + "\"";
           } else {
               System.out.println("os not supported");
           }
           Runtime rt = Runtime.getRuntime();
           System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
           Process proc = rt.exec(cmd);
           // any error message?
           StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
           // any output?
           StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
           // kick them off
           errorGobbler.start();
           outputGobbler.start();
           // any error???
           exitVal = proc.waitFor();
           System.out.println("ExitValue: " + exitVal);
       } catch (final Throwable t) {
           t.printStackTrace();
           JOptionPane.showMessageDialog(RuntimeDemo.this.btRun, "Error");
           btRun.setEnabled(true);
       }
       return exitVal;
   }
   public static void main(final String[] args) {
       Runnable gui = new Runnable() {
           public void run() {
               new RuntimeDemo().setVisible(true);
           }
       };
       //GUI must start on EventDispatchThread:
       SwingUtilities.invokeLater(gui);
   }
   class StreamGobbler extends Thread {
       InputStream is;
       String type;
       OutputStream os;
       StreamGobbler(final InputStream is, final String type) {
           this(is, type, null);
       }
       StreamGobbler(final InputStream is, final String type, final OutputStream redirect) {
           this.is = is;
           this.type = type;
           this.os = redirect;
       }
       @Override
       public void run() {
           try {
               PrintWriter pw = null;
               if (os != null) {
                   pw = new PrintWriter(os);
               }
               InputStreamReader isr = new InputStreamReader(is);
               BufferedReader br = new BufferedReader(isr);
               String line = null;
               while ((line = br.readLine()) != null) {
                   if (pw != null) {
                       pw.println(line);
                   }
                   final String lineOut = line;
                   textarea.append(type + ">" + lineOut + "\n");
               }
               if (pw != null) {
                   pw.flush();
               }
           } catch (final IOException ioe) {
               ioe.printStackTrace();
           }
       }
   }

}</code=java>