Android 開發文件對檔案訪問權限的描述向來有點含糊,於是我寫了個小例子:一支應用建立檔案,另一支應用去讀它,看看究竟誰能存取。
以 MODE_PRIVATE 建立檔案時,API 的說明是:預設模式,建立的檔案只能被呼叫的應用(或所有共用同一個 user ID 的應用)存取。多數教學則直接寫成「私有,只能被應用本身訪問」。
public void save(String filename, String content) throws Exception {
FileOutputStream out = context.openFileOutput(filename, Context.MODE_PRIVATE);
out.write(content.getBytes());
out.close();
}
再寫一支測試程式去讀 123.txt:
public class FileotherActivityTest extends AndroidTestCase {
private static final String TAG = "FileotherActivityTest";
public void testAccessOtherAppFile() throws Exception {
String path = "/data/data/com.android/files/123.txt";
File file = new File(path);
FileInputStream in = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (-1 != (len = in.read(buffer))) {
out.write(buffer, 0, len);
}
byte[] data = out.toByteArray();
out.close();
in.close();
Log.i(TAG, new String(data));
}
}
結果很有意思:以應用身分去訪問時讀不到 123.txt,但跑這個 AndroidJUnit test case 時,logcat 卻正常印出了檔案內容。
簡單分析後,我認為這正好印證了 API 裡那句「all applications sharing the same user ID」:MODE_PRIVATE 建立的檔案,除了建立者本身,凡是共用同一個 user ID 的應用都能讀。而這裡的 user ID,我理解是指同一台實機或同一個模擬器的環境,測試程式與應用同處一個環境,所以才讀得到。