1. 程式人生 > 程式設計 >android開發實現檔案讀寫

android開發實現檔案讀寫

本文例項為大家分享了android實現檔案讀寫的具體程式碼,供大家參考,具體內容如下

讀取

/**
* 檔案讀取
* @param is 檔案的輸入流
* @return 返回檔案陣列
*/
private byte[] read(InputStream is) {
  //緩衝區inputStream
  BufferedInputStream bis = null;
  //用於儲存資料
  ByteArrayOutputStream baos = null;
  try {
    //每次讀1024
    byte[] b = new byte[1024];
    //初始化
    bis = new BufferedInputStream(is);
    baos = new ByteArrayOutputStream();
    
    int length;
    while ((length = bis.read(b)) != -1) {
      //bis.read()會將讀到的資料新增到b陣列
      //將陣列寫入到baos中
      baos.write(b,length);
    }
    return baos.toByteArray();

  } catch (IOException e) {
    e.printStackTrace();
  } finally {//關閉流
    try {
      if (bis != null) {
        bis.close();
      }
      if (is != null) {
        is.close();
      }

      if (baos != null) baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return null;
}

寫入

/**
 * 將資料寫入檔案中
 * @param buffer 寫入資料
 * @param fos  檔案輸出流
 */
private void write(byte[] buffer,FileOutputStream fos) {
  //緩衝區OutputStream
  BufferedOutputStream bos = null;
  try {
    //初始化
    bos = new BufferedOutputStream(fos);
    //寫入
    bos.write(buffer);
    //重新整理緩衝區
    bos.flush();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {//關閉流
    try {
      if (bos != null) {
        bos.close();
      }
      if (fos != null) {
        fos.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

使用

//獲取檔案輸入流
InputStream mRaw = getResources().openRawResource(R.raw.core);

//讀取檔案
byte[] bytes = read(mRaw);

//建立檔案(getFilesDir()路徑在data/data/<包名>/files,需要root才能看到路徑)
File file = new File(getFilesDir(),"hui.mp3");
boolean newFile = file.createNewFile();

//寫入
if (bytes != null) {
 FileOutputStream fos = openFileOutput("hui.mp3",Context.MODE_PRIVATE);
 write(bytes,fos);
}

該步驟為耗時操作,最好在io執行緒執行

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。