Android修改文件重启以后文件被还原

一、概述

        在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){
    请求成功
}
 

      有用的话请给赞



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值