眾所周知Android有一套自己的安全模型, 具體可參見Android開發文檔。當應用程式(.apk)在安裝時就會分配一個userid,
當該應用要去訪問其他資源比如檔案的時候,就需要userid匹配。
預設情況下 ,任何應用程式建立的檔案,資料庫, sharedpreferences都應該是私人的(位於/data/data/your_project/files/),
程式私人的資料的預設路徑為/data/data/your_project/files/;
其餘程式無法訪問。除非在創 建時指明是MODE_WORLD_READABLE 或者 MODE_WORLD_WRITEABLE,只有這樣其餘程式才能正確訪問。
因為Android有這種為讀寫檔案而提供的安全保障體系(進程開啟程式私人檔案時,Android要求檢查進程的user id);
所以我們不能直接用java的api來開啟程式的私人檔案。比如:
1. FileReader file = new FileReader("Android.txt"); 上面的代碼將不能成功執行。
這裡特彆強調私人資料!言外之意是如果某個檔案或者資料不是程式私人的,既訪問它時無須經過Android的許可權檢查,那麼還是可以用java的 io api來直接存取的。所謂的非私人資料是只放在sdcard上的檔案或者資料,
可以用java的io api來直接開啟sdcard上檔案。
1. FileReader file = new FileReader("/sdcard/Android.txt");
如果要開啟程式自己私人的檔案和資料,那必須使用Activity提供openFileOutput和openFileInput方法。
建立程式私人的檔案,由於許可權方面的要求,必須使用activity提供的檔案操作方法
1. FileOutputStream os = this.openFileOutput("Android.txt", MODE_PRIVATE);
2. OutputStreamWriter outWriter = new OutputStreamWriter (os);
讀取程式私人的檔案,由於許可權方面的要求,必須使用activity提供的檔案操作方法 1. FileInputStream os =this.openFileInput("Android.txt");
2. InputStreamReader inReader = new InputStreamReader(os);
提速檔案讀寫
其原理就是讀的時候,先把檔案的一些資料讀到緩衝中。
這樣的好處是如果讀的內容已經在緩衝中,就讀緩衝的資料。
如果沒有,就讓緩衝先從檔案讀取資料,然後再從緩衝讀資料。
寫操作與操作同理.
這樣的好處是減少對檔案的操作次數,從而達到提高效能的目的。
壞處是要額外的記憶體來做緩衝區.
對於FileInputStream和FileOutputStream用下面的方式。
BufferedInputStream buf = new BufferedInputStream(new FileInputStream("file.java"));
BufferedOutputStream buf = new BufferedOutputStream(new FileOutputStream("file.java"));
對於FileReader和FileReader用下面的方式
BufferedReader buf = new BufferedReader(new FileReader("file.java"));
BufferedWriter buf = new BufferedWriter(new FileWriter("file.java"));
對於寫操作最後最好加上flush().
執行個體1:
void write2File()
{
String content="hello:"+System.currentTimeMillis();
FileOutputStream os=null;
String fileName="hubin.txt";
int mode=Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE;
try{
os=openFileOutput(fileName, mode);
os.write(content.getBytes());
/*OutputStreamWriter outWriter = new OutputStreamWriter (os);
outWriter.write(content);*/
Log.i(tag, "write:"+content);
}catch(FileNotFoundException e)
{
Log.e(tag, "createFile:",e);
}
catch(IOException e)
{
Log.e(tag, "write file",e);
}
finally
{
if(os!=null)
{
try{
os.flush();
os.close();
}catch(IOException e)
{
Log.e(tag, "close file",e);
}
}
}
}
void readFromFile()
{
String content;
FileInputStream is=null;
String fileName="hubin.txt";
try{
is=openFileInput(fileName);
byte buffer[]=new byte[is.available()];
is.read(buffer);
content=new String(buffer);
Log.i(tag, "read:"+content);
//InputStreamReader inReader = new InputStreamReader(is);
}catch(FileNotFoundException e)
{
Log.e(tag, "createFile:",e);
}
catch(IOException e)
{
Log.e(tag, "write file",e);
}
finally
{
if(is!=null)
{
try{
is.close();
}catch(IOException e)
{
Log.e(tag, "close file",e);
}
}
}
}