Android存儲方式之文件流

內部存儲android

內部存儲是指將應用程序中的數據以文件方式存儲到設備的內部存儲空間中(該文件位於 data/data/<packagename>/ 目錄下)。數組

通常狀況下應用保存在內存下的數據其餘應用是訪問不了的,當您但願確保用戶或其餘應用均沒法訪問您的文件時,內部存儲是最佳選擇。用戶卸載該應用的同時存儲在內存中的數據會一併刪除。緩存

getFilesDir() :返回該應用的內部目錄(data/data/<packagename>/)服務器

在應用目錄裏新建文件code

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

應用中通常會把一些數據存入緩存中,能夠減小訪問服務器的次數,節省用戶的流量內存

getCacheDir():返回該應用緩存文件的目錄(data/data/<packagename>/cache/)get

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

寫數據it

FileOutputStream openFileOutput(String name, int mode);io

/**寫文本信息到手機內存中
 * @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種file

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

讀數據

FileInputStream openFileInput(String name);

/**從手機內存中讀數據
 * @param file : 文件名
 * @return String : 返回讀到的文本信息
 */
public String readPhone(String file) throws Exception {
    /**
     * 一、開闢輸入流  
     * 二、把讀取到的流數據存放到內存流中     
     * 三、返回讀取到的信息(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 {
    /**
     * 一、判斷sdcard的狀態  
     * 二、假若有sdcard,且正常  獲取sdcard的根路徑,而且經過傳過來的文件名進行建立或者打開該文件
     * 三、寫數據到輸出流   
     * 四、關閉流
     */
    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">
相關文章
相關標籤/搜索