【发布时间】:2015-01-15 19:05:17
【问题描述】:
我有一个 Java 应用程序,它应该执行一个 sh 命令。
我的命令看起来像sudo /bin/sh -c "echo 7 > /sys/class/gpio/export",当我在计算机的命令提示符下执行它时,它可以工作,但不适用于我的 Java-Programm。
程序行如下所示:
System.out.println(CmdExecutor.execute("sudo /bin/sh -c \"echo 7 > /sys/class/gpio/export\""));
public class CmdExecutor {
public static String execute(String[] cmd) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} catch (IOException | InterruptedException e) {
}
return output.toString();
}
public static String execute(String cmd) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
} catch (IOException | InterruptedException e) {
}
return output.toString();
}
}
有人可以帮我吗?
【问题讨论】:
-
尝试 ....exec(cmd.toString());
-
很确定你需要在 sudo 时提供密码。
-
将阅读器添加到输出流中,看看是否有错误。示例您可以找到here
-
运行代码时会发生什么?您希望为 sudo 提供密码,还是应该在没有密码的情况下工作? sudo 或 shell 是否发出任何错误消息?你有例外吗?什么是异常和堆栈跟踪?
-
也许这会有所帮助? stackoverflow.com/questions/18708087/…