15、问:
为什么Runtime.exec("ls")没有任何输出?
答:
调用
Runtime.exec方法将产生一个本地的进程,并返回一个Process子类的实例,该实例可用于控制进程或取得进程的相关信息.
由于调用Runtime.exec方法所创建的子进程没有自己的终端或控制台,因此该子进程的标准IO(如stdin,stdou,stderr)都通过
Process.getOutputStream(),Process.getInputStream(),
Process.getErrorStream()方法重定向给它的父进程了.用户需要用这些stream来向 子进程输入数据或获取子进程的输出.
所以正确执行Runtime.exec("ls")的例程如下:
try
{
process = Runtime.getRuntime().exec (command);
InputStreamReader ir=newInputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader (ir);
String line;
while ((line = input.readLine ()) != null)
System.out.println(line);
}
catch (java.io.IOException e){
System.err.println ("IOException " + e.getMessage());
}
===================================================
例子:
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();
}
}
}
阅读(1696) | 评论(0) | 转发(0) |