歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android文件訪問權限問題

Android文件訪問權限問題

日期:2017/3/1 11:07:09   编辑:Linux編程

在Android開發,對於文件的訪問權限中說明我感覺不是很清楚,用了一個小例子來說明android創建文件,用另外一個應用去訪問創建的文件。

在android文件創建的模式中使用MODE_PRIVATE創建文件,API中的解釋如下:

File creation mode: the default mode, wherethe created file can only be accessed by the calling application (or allapplications sharing the same user ID)。

對於我的理解,對於一個應用以MODE_PRIVATE模式創建的文件只能被調用的應用(或是共享相同的用戶ID的應用)訪問。

context.MODE_PRIVATE:是默認的操作模式,它代表這個文件是私有的,只能被應用本身訪問。(網上這樣解釋的)

save方法是通過filename,content來保存文件。

  1. public void save(String filename, String content) throws Exception{
  2. FileOutputStream out = context.openFileOutput(filename, Context.MODE_PRIVATE);
  3. out.write(content.getBytes());
  4. out.close();
  5. }

按照context.MODE_PRIVATE的解釋該filename的文件只能由該應用本身訪問。我嘗試另外寫了一個應用來對其該應用創建的文件進行訪問,創建的文件為123.txt,其屬性如下:

  1. //testAccessOtherAppFile()方法對123.txt進行訪問;位於另一項目中
  2. public class FileotherActivityTest extends AndroidTestCase {
  3. private static final String TAG = "FileotherActivityTest";
  4. public void testAccessOtherAppFile() throws Exception{
  5. String path ="/data/data/com.android/files/123.txt";
  6. File file = new File(path);
  7. FileInputStream in =new FileInputStream(file);
  8. byte[] buffer = new byte[1024];
  9. int len = 0;
  10. ByteArrayOutputStream out = new ByteArrayOutputStream();
  11. while(-1 != (len = in.read(buffer))){
  12. out.write(buffer, 0, len);
  13. }
  14. //得到文件的二進制數據
  15. byte[] data = out.toByteArray();
  16. out.close();
  17. in.close();
  18. Log.i(TAG, new String(data));
  19. }
  20. }

testAccessOtherAppFile方法應用不能訪問到123.txt,但是在運行這個androidjunit testcase的時候logcat正常輸出了文件內容:



簡單的分析了下原因,在這兩個應用中是不是說明API中的all applications sharing the same user ID,private模式創建的文件可以由創建該文件的應用訪問以及與使用user ID的所有應用所訪問,這裡的user ID,我理解的是:物理機器的環境或是同一模擬器。所以,正常訪問到另一應用創建的文件。

兩個項目的目錄結構:

Copyright © Linux教程網 All Rights Reserved