獲取儲存路徑以及讀寫
阿新 • • 發佈:2019-02-08
首先給大家介紹兩個方法,getFilesDir()和getCacheDir()
getCacheDir()方法用於獲取/data/data/cache目錄
getFilesDir()方法用於獲取/data/data/files目錄
然後我們看看怎麼讀寫getFilesDir方法對應路徑下的檔案,系統提供了兩個方法openFileOutput()和openFileInput()。
/**將資料寫入系統預設位置
* @param text
* 要儲存的字元
*/
public void write(String text)
{
try {
//通過openFileOutput方法得到一個輸出流,方法引數為建立的檔名(不能有斜槓),操作模式
FileOutputStream fos=this.openFileOutput("myfirst.txt", Context.MODE_WORLD_READABLE);
fos.write(text.getBytes());//寫入
fos.close(); // 關閉輸出流
//彈出Toast訊息
Toast.makeText(MainActivity.this,"儲存成功",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
/**讀取檔案*/
public void read()
{
try {
FileInputStream fis=this.openFileInput("myfirst.txt"); //獲得輸入流
//用來獲得記憶體緩衝區的資料,轉換成位元組陣列
ByteArrayOutputStream stream=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int length=-1;
while((length=fis.read(buffer))!=-1 ) {
stream.write(buffer,0,length);//獲取記憶體緩衝區中的資料
}
stream.close(); //關閉
fis.close();
tv.setText(stream.toString()); //設定文字控制元件顯示內容
Toast.makeText(MyFile.this,"讀取成功",Toast.LENGTH_LONG).show();//彈出Toast訊息
} catch (FileNotFoundException e) {
Toast.makeText(MyFile.this, "檔案不存在", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}