新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > Android文件訪問權(quán)限問題

Android文件訪問權(quán)限問題

作者: 時(shí)間:2016-09-12 來源:網(wǎng)絡(luò) 收藏

在android開發(fā),對(duì)于文件的訪問權(quán)限中說明我感覺不是很清楚,用了一個(gè)小例子來說明android創(chuàng)建文件,用另外一個(gè)應(yīng)用去訪問創(chuàng)建的文件。

本文引用地址:http://www.2s4d.com/article/201609/305202.htm

在android文件創(chuàng)建的模式中使用MODE_PRIVATE創(chuàng)建文件,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)。

對(duì)于我的理解,對(duì)于一個(gè)應(yīng)用以MODE_PRIVATE模式創(chuàng)建的文件只能被調(diào)用的應(yīng)用(或是共享相同的用戶ID的應(yīng)用)訪問。

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

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

public void save(String filename, String content) throws Exception{

out = context.openFileOutput(filename, Context.MODE_PRIVATE);

out.write(content.getBytes());

out.close();

}

按照context.MODE_PRIVATE的解釋該filename的文件只能由該應(yīng)用本身訪問。我嘗試另外寫了一個(gè)應(yīng)用來對(duì)其該應(yīng)用創(chuàng)建的文件進(jìn)行訪問,創(chuàng)建的文件為123.txt,其屬性如下:

//testAccessOtherAppFile()方法對(duì)123.txt進(jìn)行訪問;位于另一項(xiàng)目中

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);

}

//得到文件的二進(jìn)制數(shù)據(jù)

byte[] data = out.toByteArray();

out.close();

in.close();

Log.i(TAG, new String(data));

}

}

testAccessOtherAppFile方法應(yīng)用不能訪問到123.txt,但是在運(yùn)行這個(gè)androidjunit testcase的時(shí)候logcat正常輸出了文件內(nèi)容:

簡(jiǎn)單的分析了下原因,在這兩個(gè)應(yīng)用中是不是說明API中的all applications sharing the same user ID,private模式創(chuàng)建的文件可以由創(chuàng)建該文件的應(yīng)用訪問以及與使用user ID的所有應(yīng)用所訪問,這里的user ID,我理解的是:物理機(jī)器的環(huán)境或是同一模擬器。所以,正常訪問到另一應(yīng)用創(chuàng)建的文件。

兩個(gè)項(xiàng)目的目錄結(jié)構(gòu):



關(guān)鍵詞:

評(píng)論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉