Android Runtime.getRuntime().exec(…),参数带有空格的解决方法
解决方法
/**
* linux 命令移动文件 (最好不要再主线程调用)
* @param srcFile 源文件
* @param desSrc 目标文件
* @return 返回是否移动成功
*/
public static boolean moveFile(String srcFile, String desSrc) {
try {
String moveCommand = String.format("mv %s %s", srcFile, desSrc);
moveCommand = "\""+moveCommand +"\""; ***//命令要用双引号括起来***
moveCommand = moveCommand .replaceAll(" ","\" \""); ***//所有空格都需要加双引号***
Log.e(TAG, "moveFile moveCommand: " + moveCommand);
Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", moveCommand});
process.waitFor();//等待进程结束(阻塞)
Log.e(TAG, "moveFile: move end ...");
return !(new File(srcFile).exists());//源文件不存在即可认为移动成功
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
使用重载函数即可:
public Process exec(String cmdarray[]);
Process ps = Runtime.getRuntime().exec(new String[]{“/bin/sh”, “-c”, cmd});
ps.waitFor();
其中-c表示cmd是一条命令
/bin/sh -c注意事项
由于增加了-c 参数,并指定shell类型,因此需要确认shell的类型。因此根据实际环境的shell类型。
/bin/sh是什么?
shell编程是以"#“为注释,但对”#!/bin/sh"却不是。"#!/bin/sh"是对shell的声明,说明你所用的是那种类型的shell及其路径所在(#! /bin/sh 是指此脚本使用/bin/sh来解释执行,#!是特殊的表示符,其后面跟的是解释此脚本的shell的路径)。如果没有声明,则脚本将在默认的shell中执行,默认shell是由用户所在的系统定义为执行shell脚本的shell。
如果脚本被编写为在Kornshell ksh中运行,而默认运行shell脚本的为C shell csh,则脚本在执行过程中很可能失败。所以建议大家就把"#!/bin/sh"当成C 语言的main函数一样,写shell必须有,以使shell程序更严密。