android資料儲存的四種方案(二)
檔案流操作
二.openFileOutput和openFileInput
openFileOutput : 開啟要寫入的檔案,返回一個OutputStream物件
openFileInput:開啟要讀取的檔案,返回一個InputStream物件
這兩個Stream物件的建立過程類似於SharedPreferences物件的初始化過程:
OutputStream os = openFileOutput("file.txt",Activity.MODE_PRIVATE);
InputStream is = openFileInput("file.txt");
區別只是第一個引數多了一個副檔名
無論是SharedPreferences還是今天說的這兩個,他們在初始化時都是僅僅指定了檔名,而不是檔案路徑,所以,他們只能將檔案儲存到固定的路徑對於OutputStream和InputStream將檔案儲存在DDMS裡的File explore的data/data//files目錄,SharedPreferences將檔案儲存在data/data//shared_prefs中.
具體來看一個小例子:
public void onClick(){
try {
//開啟要寫入的檔案
OutputStream os = openFileOutput("file.txt", Activity.MODE_PRIVATE);
String str = "中國萬歲";
//將要寫入的字串轉化為位元組寫入
os.write(str.getBytes("utf-8"));
os.close();
//開啟要讀取的資料夾
InputStream is = openFileInput("file.txt");
byte [] buffer = new byte[128];
int byteCount = is.read(buffer);
//將讀取到的位元組轉化為字串
String str1 = new String(buffer, 0, byteCount, "utf-8");
Toast.makeText(getApplicationContext(), str1, 2).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
注:雖然openFileOutput,openFileInput方法可以獲得outputStream以及InputStream物件,且可以通過流物件人已處理資料,但是跟SharedPreferences一樣只能在手機記憶體卡的指定目錄儲存資料,都存在侷限性,所以接下來看一種更高階的讀寫SD卡的方法
讀取SD卡中的檔案
FileOutputStream和FileInputStream用來讀取指定路徑的檔案
這裡直接上程式碼吧,這次是將android工程裡的assets目錄裡的text.png
圖片存入SD卡,點選按鈕後再從SD卡中取出該圖片並設定給ImageView
try{
//建立FileOutputStream物件用於將檔案寫入SD卡
FileOutputStream fos = new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + "/picture.png");
//讀取assetc目錄中的圖片返回一個InputStream物件
InputStream is = getResources().getAssets().open("text.png");
//一次寫8k
byte[] buffer = new byte[8192];
int count = 0;
while((count = is.read(buffer)) >= 0){
fos.write(buffer, 0, count);
}
//重新整理流
fos.flush();
//關閉流
fos.close();
is.close();
//至此圖片已經存入SD卡
}catch(Exception e){
e.printStackTrace();
}
public void onClick(View view){
//指定讀取位置
String fileName = android.os.Environment.getExternalStorageDirectory() + "/picture.png";
try {
//判斷圖片是否存在
if(!new File(fileName).exists()){
Toast.makeText(getApplicationContext(), "找不到資料", 1).show();
return;
}
//獲取fis物件用來讀取SD卡中的資料(這裡是圖片)
FileInputStream fis = new FileInputStream(fileName);
imageView = (ImageView)findViewById(R.id.imageView1);
//利用圖片工廠獲取圖片
Bitmap bitmap = BitmapFactory.decodeStream(fis);
imageView.setImageBitmap(bitmap);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
注:我們一般獲取SD卡路徑除了用andorid.os.Enviroment.getExternalStorageDirectory方法,還可以直接使用“/sdcard”,但是建議使用前者,這樣一旦系統改變了路徑,應用程式會立刻獲得最新的路徑,使程式更健壯
最後還需要加許可權
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"