RuntimeDemo: Unterschied zwischen den Versionen

Aus Byte-Welt Wiki
Zur Navigation springenZur Suche springen
K
 
(4 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
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.
+
Die [[Klasse]] {{JAPI|java.lang.Runtime}} besitzt die statische Methode <code>getRuntime()</code>, die das [[Java Runtime Environment]] zurückgibt. Mit dieser [[Referenz]] können wir externe Programme ausführen, indem wir die <code>exec()</code>-[[Methode]] der Klasse Runtime aufrufen.
<code=java>/*
+
<syntaxhighlight lang="java">
 +
/*
 
  * RuntimeDemo.java
 
  * RuntimeDemo.java
 
  * The class java.lang.Runtime features a static method called getRuntime(),  
 
  * The class java.lang.Runtime features a static method called getRuntime(),  
Zeile 7: Zeile 8:
 
  *
 
  *
 
  */
 
  */
 
 
import java.awt.*;
 
import java.awt.*;
 
import java.awt.event.*;
 
import java.awt.event.*;
 
import java.io.*;
 
import java.io.*;
 +
import java.util.logging.*;
 
import javax.swing.*;
 
import javax.swing.*;
  
public class RuntimeDemo extends JFrame {
+
public class RuntimeDemo {
  
 
     private JButton btRun;
 
     private JButton btRun;
Zeile 22: Zeile 23:
  
 
     public RuntimeDemo() {
 
     public RuntimeDemo() {
         super("RuntimeDemo");
+
         JFrame f = new JFrame("RuntimeDemo");
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+
         f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
 
         toolbar = new JToolBar();
 
         toolbar = new JToolBar();
 
         lbCommand = new JLabel("Command: ");
 
         lbCommand = new JLabel("Command: ");
Zeile 35: Zeile 36:
 
         btRun.addActionListener(new ActionListener() {
 
         btRun.addActionListener(new ActionListener() {
  
 +
            @Override
 
             public void actionPerformed(final ActionEvent evt) {
 
             public void actionPerformed(final ActionEvent evt) {
 
                 btRunActionPerformed(evt);
 
                 btRunActionPerformed(evt);
Zeile 40: Zeile 42:
 
         });
 
         });
 
         toolbar.add(btRun);
 
         toolbar.add(btRun);
         getContentPane().add(toolbar, BorderLayout.PAGE_START);
+
         f.getContentPane().add(toolbar, BorderLayout.PAGE_START);
         getContentPane().add(new JScrollPane(textarea), BorderLayout.CENTER);
+
         f.getContentPane().add(new JScrollPane(textarea), BorderLayout.CENTER);
         setSize(800, 600);
+
         f.setSize(800, 600);
         setLocationRelativeTo(null);
+
         f.setLocationRelativeTo(null);
 +
        f.setVisible(true);
 
     }
 
     }
  
Zeile 71: Zeile 74:
 
             String osName = System.getProperty("os.name");
 
             String osName = System.getProperty("os.name");
 
             String[] cmd = new String[3];
 
             String[] cmd = new String[3];
             System.out.println(osName);
+
             Logger.getLogger("log").log(Level.INFO, osName);
 
             if (osName.equals("Windows XP") || osName.equals("Windows NT")) {
 
             if (osName.equals("Windows XP") || osName.equals("Windows NT")) {
 
                 cmd[0] = "cmd.exe";
 
                 cmd[0] = "cmd.exe";
Zeile 77: Zeile 80:
 
                 cmd[2] = "\"" + command + "\"";
 
                 cmd[2] = "\"" + command + "\"";
 
             } else {
 
             } else {
                 System.out.println("os not supported");
+
                 Logger.getLogger("log").log(Level.INFO, "os not supported");
 
             }
 
             }
 
 
             Runtime rt = Runtime.getRuntime();
 
             Runtime rt = Runtime.getRuntime();
             System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
+
             Logger.getLogger("log").log(Level.INFO, "Execing {0} {1} {2}", new Object[]{cmd[0], cmd[1], cmd[2]});
 
             Process proc = rt.exec(cmd);
 
             Process proc = rt.exec(cmd);
 
             // any error message?
 
             // any error message?
 
             StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
 
             StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
 
 
             // any output?
 
             // any output?
 
             StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
 
             StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
 
 
             // kick them off
 
             // kick them off
 
             errorGobbler.start();
 
             errorGobbler.start();
 
             outputGobbler.start();
 
             outputGobbler.start();
 
 
             // any error???
 
             // any error???
 
             exitVal = proc.waitFor();
 
             exitVal = proc.waitFor();
             System.out.println("ExitValue: " + exitVal);
+
             Logger.getLogger("log").log(Level.INFO, "ExitValue: {0}", exitVal);
 
         } catch (final Throwable t) {
 
         } catch (final Throwable t) {
             t.printStackTrace();
+
             Logger.getLogger("log").log(Level.SEVERE, null, t);
 
             JOptionPane.showMessageDialog(RuntimeDemo.this.btRun, "Error");
 
             JOptionPane.showMessageDialog(RuntimeDemo.this.btRun, "Error");
 
             btRun.setEnabled(true);
 
             btRun.setEnabled(true);
Zeile 107: Zeile 106:
 
         Runnable gui = new Runnable() {
 
         Runnable gui = new Runnable() {
  
 +
            @Override
 
             public void run() {
 
             public void run() {
                 new RuntimeDemo().setVisible(true);
+
                 RuntimeDemo runtimeDemo = new RuntimeDemo();
 
             }
 
             }
 
         };
 
         };
 
         //GUI must start on EventDispatchThread:
 
         //GUI must start on EventDispatchThread:
         SwingUtilities.invokeLater(gui);
+
         EventQueue.invokeLater(gui);
 
     }
 
     }
  
     class StreamGobbler extends Thread {
+
     private class StreamGobbler extends Thread {
  
         InputStream is;
+
         private InputStream is;
         String type;
+
         private String type;
         OutputStream os;
+
         private OutputStream os;
  
 
         StreamGobbler(final InputStream is, final String type) {
 
         StreamGobbler(final InputStream is, final String type) {
Zeile 138: Zeile 138:
 
                     pw = new PrintWriter(os);
 
                     pw = new PrintWriter(os);
 
                 }
 
                 }
 
 
                 InputStreamReader isr = new InputStreamReader(is);
 
                 InputStreamReader isr = new InputStreamReader(is);
 
                 BufferedReader br = new BufferedReader(isr);
 
                 BufferedReader br = new BufferedReader(isr);
 
                 String line = null;
 
                 String line = null;
                 while ((line = br.readLine()) != null) {
+
                 line = br.readLine();
 +
                while (line != null) {
 
                     if (pw != null) {
 
                     if (pw != null) {
 
                         pw.println(line);
 
                         pw.println(line);
Zeile 148: Zeile 148:
 
                     final String lineOut = line;
 
                     final String lineOut = line;
 
                     textarea.append(type + ">" + lineOut + "\n");
 
                     textarea.append(type + ">" + lineOut + "\n");
 +
                    line = br.readLine();
 
                 }
 
                 }
 
                 if (pw != null) {
 
                 if (pw != null) {
Zeile 153: Zeile 154:
 
                 }
 
                 }
 
             } catch (final IOException ioe) {
 
             } catch (final IOException ioe) {
                 ioe.printStackTrace();
+
                 Logger.getLogger("log").log(Level.SEVERE, null, ioe);
 
             }
 
             }
 
         }
 
         }
 
     }
 
     }
}</code=java>
+
}
[[Kategorie:Java]]
+
</syntaxhighlight>
 +
 
 +
Viele externe Programme lassen sich aber heute deutlich komfortabler mit Hilfe der Klasse {{JAPI|Desktop}} ausführen.
 +
 
 
[[Kategorie:Tutorials (Java)]]
 
[[Kategorie:Tutorials (Java)]]
 
[[Kategorie:Java-Codeschnipsel]]
 
[[Kategorie:Java-Codeschnipsel]]

Aktuelle Version vom 22. Dezember 2018, 10:03 Uhr

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.

/*
 * 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 java.util.logging.*;
import javax.swing.*;

public class RuntimeDemo {

    private JButton btRun;
    private JLabel lbCommand;
    private JTextArea textarea;
    private JTextField tfCommand;
    private JToolBar toolbar;

    public RuntimeDemo() {
        JFrame f = new JFrame("RuntimeDemo");
        f.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() {

            @Override
            public void actionPerformed(final ActionEvent evt) {
                btRunActionPerformed(evt);
            }
        });
        toolbar.add(btRun);
        f.getContentPane().add(toolbar, BorderLayout.PAGE_START);
        f.getContentPane().add(new JScrollPane(textarea), BorderLayout.CENTER);
        f.setSize(800, 600);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    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];
            Logger.getLogger("log").log(Level.INFO, osName);
            if (osName.equals("Windows XP") || osName.equals("Windows NT")) {
                cmd[0] = "cmd.exe";
                cmd[1] = "/C";
                cmd[2] = "\"" + command + "\"";
            } else {
                Logger.getLogger("log").log(Level.INFO, "os not supported");
            }
            Runtime rt = Runtime.getRuntime();
            Logger.getLogger("log").log(Level.INFO, "Execing {0} {1} {2}", new Object[]{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();
            Logger.getLogger("log").log(Level.INFO, "ExitValue: {0}", exitVal);
        } catch (final Throwable t) {
            Logger.getLogger("log").log(Level.SEVERE, null, t);
            JOptionPane.showMessageDialog(RuntimeDemo.this.btRun, "Error");
            btRun.setEnabled(true);
        }
        return exitVal;
    }

    public static void main(final String[] args) {
        Runnable gui = new Runnable() {

            @Override
            public void run() {
                RuntimeDemo runtimeDemo = new RuntimeDemo();
            }
        };
        //GUI must start on EventDispatchThread:
        EventQueue.invokeLater(gui);
    }

    private class StreamGobbler extends Thread {

        private InputStream is;
        private String type;
        private 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;
                line = br.readLine();
                while (line != null) {
                    if (pw != null) {
                        pw.println(line);
                    }
                    final String lineOut = line;
                    textarea.append(type + ">" + lineOut + "\n");
                    line = br.readLine();
                }
                if (pw != null) {
                    pw.flush();
                }
            } catch (final IOException ioe) {
                Logger.getLogger("log").log(Level.SEVERE, null, ioe);
            }
        }
    }
}

Viele externe Programme lassen sich aber heute deutlich komfortabler mit Hilfe der Klasse Desktop ausführen.