执行shell 命令的方法
- 开发中遇到的需要给驱动节点赋值,而这个驱动节点的目录在/sys/devices/platform/… 的目录下,目标文件需要有 chmod 777 授权;执行代码前可以在自带的命令行Terminal里先执行下shell命令,看看有作用了,再迁移到Java 代码中。
public static final String COMMAND_HDMI_STATE_1 = "echo 1 > /sys/devices/platform/...\n";
public static String execRootCmd() {
String result = "";
DataOutputStream dos = null;
DataInputStream dis = null;
try {
Process p = Runtime.getRuntime().exec("sh");
dos = new DataOutputStream(p.getOutputStream());
dis = new DataInputStream(p.getInputStream());
dos.writeBytes(COMMAND_HDMI_STATE_1);
dos.flush();
dos.writeBytes("exit\n");
dos.flush();
String line = null;
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
while ((line = br.readLine()) != null) {
result += line;
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}