1. 程式人生 > 其它 >Android修改檔案重啟以後檔案被還原怎麼辦

Android修改檔案重啟以後檔案被還原怎麼辦

技術標籤: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){
    請求成功
}

有用的話請給贊