首页新闻找找看学习计划

java 抛IO异常 用runtime.exec 执行linux命令

0
悬赏园豆:10 [已关闭问题] 关闭于 2013-09-03 15:01
java 抛IO异常  

java.io.IOException: 断开的管道
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:318)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:297)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:141)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:229)
at com.zehin.util.exec.ExecuteCommand.re_excuteCommand(ExecuteCommand.java:60)

命令比如 command="sudo echo 111 > 123.txt"
re_excuteCommand方法如下
public static void re_excuteCommand(String command) {
try {
Vector<String> commands = new Vector<String>();
commands.add("/bin/bash");
commands.add("-c");
commands.add(command);
ProcessBuilder p = new ProcessBuilder(commands);
Process process = p.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
OutputStreamWriter out = new OutputStreamWriter(
process.getOutputStream());
out.write("123456");//这个是ubuntu的密码
out.flush();
out.close();
System.out.println("BASHPID=" + line);

br.close();
isr.close();
is.close();
process.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Jghost的主页 Jghost | 菜鸟二级 | 园豆:204
提问于:2013-05-13 14:38
< >
分享
所有回答(1)
0
public static void re_excuteCommand(String command) {
try {
Vector<String> commands = new Vector<String>();
commands.add("/bin/bash");
commands.add("-c");
commands.add(command);
ProcessBuilder p = new ProcessBuilder(commands);
Process process = p.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
OutputStreamWriter out = new OutputStreamWriter(
process.getOutputStream());
//out.write("123456");//这个是ubuntu的密码
//out.flush();
out.close();
System.out.println("BASHPID=" + line);

br.close();
isr.close();
is.close();
process.destroy();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

 必须root运行这段程序 才不会出错

 
Jghost | 园豆:204 (菜鸟二级) | 2013-09-03 15:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册