Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1203779
  • 博文数量: 181
  • 博客积分: 6155
  • 博客等级: 准将
  • 技术积分: 1805
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-05 09:24
文章分类

全部博文(181)

文章存档

2015年(2)

2014年(3)

2013年(9)

2012年(29)

2011年(30)

2010年(36)

2009年(40)

2008年(32)

分类: LINUX

2010-04-09 17:19:39

 Executing a CommandSee also .

try {
// Execute a command without arguments
String command = "ls";
Process child = Runtime.getRuntime().exec(command);

// Execute a command with an argument
command = "ls /tmp";
child = Runtime.getRuntime().exec(command);
} catch (IOException e) {
}

If an argument contain spaces, it is necessary to use the overload that requires the command and its arguments to be supplied in an array:

try {
// Execute a command with an argument that contains a space
String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};
commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e) {
}

e90. Reading Output from a Command

try {
// Execute command
String command = "ls";
Process child = Runtime.getRuntime().exec(command);

// Get the input stream and read from it
InputStream in = child.getInputStream();
int c;
while ((c = in.read()) != -1) {
process((char)c);
}
in.close();
} catch (IOException e) {
}

 

e91. Sending Input to a Command

try {
// Execute command
String command = "cat";
Process child = Runtime.getRuntime().exec(command);

// Get output stream to write from it
OutputStream out = child.getOutputStream();

out.write("some text".getBytes());
out.close();
} catch (IOException e) {
}


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