一、概述
在Android开发中,我们对文件进行操作后,例如拷贝,修改等等。直接断电重启,重启后发现文件还是原来的样子,可是打Log看之前明明是修改成功了。这是因为Linux系统中文件系统机制,我们在进行文件操作后,需要进行sync操作才可以使文件真正的被修改。
二、如何执行SYNC来同步Android文件系统
在执行完关键的文件操作后,调用sync命令,sync命令是给Linux的。如果不知道怎么在Android中发shell命令的话,我下面封装了一个方法。
/**
*
* @param commands 命令字符串
* @param commondModel 是"su"还是"sh", "su"需要root权限
* @return 返回-1的话说明命令执行错误了
*/
public static int execCommand(String[] commands,String commondModel) {
int result = -1;
if (commands == null || commands.length == 0) {
Log.v(TAG,"请求命令错误");
return -1;
}
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec(commondModel);
os = new DataOutputStream(process.getOutputStream());
StringBuilder commandStr = new StringBuilder("");
for (String command : commands) {
if (command == null) {
continue;
}
commandStr.append(command);
commandStr.append("\n");
}
Log.i(TAG,"execCommand: 请求执行的命令:" + commandStr);
os.write(commandStr.toString().getBytes());
os.flush();
os.writeBytes("exit\n");
os.flush();
result = process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
return result;
}
例如我们这里执行的是"sync",执行"sync"是不用root权限的,所以使用"sh"就够了
使用实例:
String[] sync={"sync"};
int result = execCommand(sync,"sh");
if(result!=-1){
请求成功
}
有用的话请给赞