Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3350808
  • 博文数量: 1450
  • 博客积分: 11163
  • 博客等级: 上将
  • 技术积分: 11101
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-25 14:40
文章分类

全部博文(1450)

文章存档

2017年(5)

2014年(2)

2013年(3)

2012年(35)

2011年(39)

2010年(88)

2009年(395)

2008年(382)

2007年(241)

2006年(246)

2005年(14)

分类: LINUX

2007-03-02 17:14:38

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();
}
}

}
阅读(1659) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~