|
三、捕获其他程序的控制台输出
在JTextArea中捕获Java程序自己的控制台输出是一回事,去捕获其他程序(甚至包括一些非Java程序)的控制台数据又是另一回事。ConsoleTextArea提供了捕获其他应用的输出时需要的基础功能,Listing
6的AppOutputCapture利用ConsoleTextArea,截取其他应用的输出信息然后显示在ConsoleTextArea中。
【Listing 6:截获其他程序的控制台输出】
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class AppOutputCapture {
private static Process process;
public static void main(String[] args) {
if(args.length == 0) {
System.err.println("用法:java AppOutputCapture " +
"<程序名字> {参数1 参数2 ...}");
System.exit(0);
}
try {
// 启动命令行指定程序的新进程
process = Runtime.getRuntime().exec(args);
}
catch(IOException e) {
System.err.println("创建进程时出错...\n" + e);
System.exit(1);
}
// 获得新进程所写入的流
InputStream[] inStreams =
new InputStream[] {
process.getInputStream(),process.getErrorStream()};
ConsoleTextArea cta = new
ConsoleTextArea(inStreams);
cta.setFont(java.awt.Font.decode("monospaced"));
JFrame frame = new JFrame(args[0] +
"控制台输出");
frame.getContentPane().add(new JScrollPane(cta),
BorderLayout.CENTER);
frame.setBounds(50, 50, 400, 400);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
process.destroy();
try {
process.waitFor(); // 在Win98下可能被挂起
}
catch(InterruptedException e) {}
System.exit(0);
}
});
} // main()
} // AppOutputCapture
AppOutputCapture的工作过程如下:首先利用Runtime.exec()方法启动指定程序的一个新进程。启动新进程之后,从结果
Process对象得到它的控制台流。之后,把这些控制台流传入ConsoleTextArea(InputStream[])构造函数(这就是带参数
ConsoleTextArea构造函数的用处)。使用AppOutputCapture时,在命令行上指定待截取其输出的程序名字。
|