天天看點

java如何運作程式_Java中運作其它程式方法的執行個體詳解

由于前段時間一個網友寫信詢問如何在運作其他可執行程式時将控制台的輸入送出到它想運作的程式,由于考慮到他的特殊情況就幫他弄了一下,剛開始想着這個問題應該比較簡單,但是在實際做的過程中才發現有很多陷阱,而且好像不能弄一個非常通用的東西出來。下面的代碼是我想做出的一個通用封裝器的嘗試:

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為範例程式和網友給我的那個程式做了對比,發現如下幾個在處理這個問題時需要注意的地方: