由于前段时间一个网友写信询问如何在运行其他可执行程序时将控制台的输入提交到它想运行的程序,由于考虑到他的特殊情况就帮他弄了一下,刚开始想着这个问题应该比较简单,但是在实际做的过程中才发现有很多陷阱,而且好像不能弄一个非常通用的东西出来。下面的代码是我想做出的一个通用封装器的尝试:
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为范例程序和网友给我的那个程序做了对比,发现如下几个在处理这个问题时需要注意的地方:
|