RuntimeDemo: Unterschied zwischen den Versionen
Aus Byte-Welt Wiki
Zur Navigation springenZur Suche springenK |
K |
||
Zeile 163: | Zeile 163: | ||
Viele externe Programme lassen sich aber heute deutlich komfortabler mit Hilfe der Klasse {{JAPI|Desktop}} ausführen. | 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.