1. 程式人生 > >Android複習之旅--檔案儲存

Android複習之旅--檔案儲存

內部儲存

內部儲存是指將應用程式中的資料以檔案方式儲存到裝置的內部儲存空間中(該檔案位於 data/data// 目錄下)。

一般情況下應用儲存在記憶體下的資料其他應用是訪問不了的,當您希望確保使用者或其他應用均無法訪問您的檔案時,內部儲存是最佳選擇。使用者解除安裝該應用的同時儲存在記憶體中的資料會一併刪除。

getFilesDir() :返回該應用的內部目錄(data/data//)

在應用目錄裡新建檔案

File file = new File(getFileDir(), filename);

應用中一般會把一些資料存入快取中,可以減少訪問伺服器的次數,節省使用者的流量

getCacheDir():返回該應用快取檔案的目錄(data/data//cache/)

File file = File.createTempFile(fileName, null, context.getCacheDir());

寫資料

FileOutputStream openFileOutput(String name, int mode);

/**寫文字資訊到手機記憶體中
 * @param filename : 檔名
 * @param body : 檔案的內容
 * @throws Exception
 */
public void writePhone(String file, String body) throws Exception {
    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(file, Context.MODE_PRIVATE);
        fos.write(body.getBytes()); //寫文字資訊到手機記憶體中
    } catch (Exception e) {
        if(fos != null){
            fos.close(); //關閉檔案輸入流
        }
    }
}

其中,mode是讀寫檔案的方式,通常使用的值有2種

  • MODE_PRIVATE:私有模式,只能被當前程式讀寫
  • MODE_APPEND:追加模式

讀資料

FileInputStream openFileInput(String name);

/**從手機記憶體中讀資料
 * @param file : 檔名
 * @return String : 返回讀到的文字資訊
 */
public String readPhone(String file) throws Exception {
    /**
     * 1、開闢輸入流  
     * 2、把讀取到的流資料存放到記憶體流中     
     * 3、返回讀取到的資訊(String的形式返回)
     */
    FileInputStream fis = context.openFileInput(file);
    //位元組陣列輸出流(記憶體流)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];//位元組陣列,快取
    int len = -1;
    while((len = fis.read(buffer)) != -1){
        //把讀取的內容寫入到記憶體流中
        baos.write(buffer, 0, len);
    }
    baos.close();
    fis.close();
    return baos.toString();
}

外部儲存

外部儲存是指將檔案儲存到一些外圍裝置上,如SDcard或裝置內嵌的儲存卡等(該檔案通常位於mnt/sdcard目錄下,由於手機有各種廠商生產,獲取SD卡根目錄一律採用Environment.getExternalStorageDirectory()這個方法)

由於外圍儲存裝置可能被移除、丟失或者處於其他狀態,所以使用外圍裝置之前要使用Environment.getExternalStorageState()方法來確認是否可用。因為外圍儲存是全域性可讀寫的,對於無需訪問限制以及您希望與其他應用共享或允許使用者使用電腦訪問的檔案,外部儲存是最佳位置。

寫資料

FileOutputStream 或 FileWriter

/**寫檔案到sdcard中
 * @param file
 * @param body
 */
public void writeSdcard(String file, String body) throws Exception {
    /**
     * 1、判斷sdcard的狀態  
     * 2、假如有sdcard,且正常  獲取sdcard的根路徑,並且通過傳過來的檔名進行建立或者開啟該檔案
     * 3、寫資料到輸出流   
     * 4、關閉流
     */
    FileOutputStream fos = null;
    try{
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        //取得sdcard的根路徑
        File rootPath = Environment.getExternalStorageDirectory();
        //建立要寫入sdcard的檔案
        File f = new File(rootPath, file);
        //開闢輸出流
        fos = new FileOutputStream(f);
        fos.write(body.getBytes());
    }finally {
        if(fos != null){
            fos.close();
        }else{
            throw new RuntimeException("sdcard狀態錯誤");
        }
    }
}

讀資料

FileInputStream 或 FileReader

/**
 * 讀取sdcard中的檔案
 * @param file
 * @return
 * @throws Exception
 */
public String readSdcard(String file) throws Exception {
    FileInputStream fis = null;
    ByteArrayOutputStream baos = null;
    try{
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //取得sdcard的根目錄
            File rootPath = Environment.getExternalStorageDirectory();
            File f = new File(rootPath.getAbsolutePath()+ "/" + file);
            if(f.exists()){ //判斷檔案是否存在
                fis = new FileInputStream(f);
                //位元組陣列輸出流(記憶體流)
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024]; //位元組陣列,快取
                int len = -1;
                while((len = fis.read(buffer)) != -1){
                    //把讀取到的內容寫入到記憶體流中
                    baos.write(buffer, 0, len);
                }
            }else{
                return null;
            } 
        }else{
            throw new RuntimeException("sdcard狀態錯誤");
        }
    } finally{
        if(baos != null){
            baos.close();
        }
        if(fis != null){
            fis.close();
        }
    }
    return baos.toString();
}

需要注意的是,讀寫外部資料時需要設定許可權

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">