Java中运行其它程序方法的实例详解
2008-01-05 20:20:47 来源:WEB开发网import java.io.*;
public class CommandWrapper
{
PRocess process;
Thread in;
Thread out;
public CommandWrapper(Process process)
{
this.process = process;
final InputStream inputStream
= process.getInputStream();
//final BufferedReader
r=new BufferedReader
(new InputStreamReader(inputStream));
final byte[] buffer = new byte[1024];
out = new Thread()
{
//String line;
int lineNumber=0;
public void run()
{
try {
while (true)
{
int count = inputStream.read(buffer);
System.out.println
(lineNumber+":"+new String
(buffer, 0, count-1));
//line=r.readLine();
//System.out.println
(lineNumber+":"+line);
lineNumber++;
}
}
catch (Exception e)
{
}
}
};
final BufferedReader reader =
new BufferedReader
(new InputStreamReader(System.in));
final OutputStream outputStream
= process.getOutputStream();
in = new Thread()
{
String line;
public void run()
{
try {
while (true)
{
outputStream.write(
(reader.readLine()+"\n").getBytes());
outputStream.flush();
}
}
catch (Exception e)
{
}
}
};
}
public void startIn()
{
in.start();
}
public void startOut()
{
out.start();
}
public void interruptIn()
{
in.interrupt();
}
public void interruptOut()
{
out.interrupt();
}
public static void main(String[] args)
{
try
{
CommandWrapper command =
new CommandWrapper(Runtime.getRuntime().
exec("native2ascii"));
command.startIn();
command.startOut();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
我以native2ascii为范例程序和网友给我的那个程序做了对比,发现如下几个在处理这个问题时需要注重的地方:
1、由于不知道目标程序的输入输出顺序,因此只能建立两个单独的线程分别处理输入和输出,这样输入和输出就不会阻塞了。 但是有些目标程序要求有特定的输入输出顺序,而经过这个类封装的结果是在任何状态下都可以输入,程序的任何输出也会被马上反映出来,构造通用类的第一个问题。
更多精彩
赞助商链接