Android之应用中执行Linux命令

下面,我以修改某一文件的权限为777为例:

/** 执行Linux命令,并返回执行结果。 */

public static String exec(String[] args) {

String result = "";

ProcessBuilder processBuilder = new ProcessBuilder(args);

Process process = null;

InputStream errIs = null;

InputStream inIs = null;

try {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int read = -1;

process = processBuilder.start();

errIs = process.getErrorStream();

while ((read = errIs.read()) != -1) {

baos.write(read);

}

baos.write('\n');

inIs = process.getInputStream();

while ((read = inIs.read()) != -1) {

baos.write(read);

}

byte[] data = baos.toByteArray();

result = new String(data);

} catch (IOException e) {

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (errIs != null) {

errIs.close();

}

if (inIs != null) {

inIs.close();

}

} catch (IOException e) {

e.printStackTrace();

}

if (process != null) {

process.destroy();

}

}

return result;

}

下面在我们需要的地方调用上面函数即可:

String[] args = { "chmod", "777", "(文件路径)"};

exec(args);

0b1331709591d260c1c78e86d0c51c18.png

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐