android開(kāi)發(fā)實(shí)現(xiàn)文件讀寫(xiě)
本文實(shí)例為大家分享了android實(shí)現(xiàn)文件讀寫(xiě)的具體代碼,供大家參考,具體內(nèi)容如下
讀取
/*** 文件讀取* @param is 文件的輸入流* @return 返回文件數(shù)組*/private byte[] read(InputStream is) { //緩沖區(qū)inputStream BufferedInputStream bis = null; //用于存儲(chǔ)數(shù)據(jù) 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()會(huì)將讀到的數(shù)據(jù)添加到b數(shù)組 //將數(shù)組寫(xiě)入到baos中 baos.write(b, 0, length); } return baos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally {//關(guān)閉流 try { if (bis != null) {bis.close(); } if (is != null) {is.close(); } if (baos != null) baos.close(); } catch (IOException e) { e.printStackTrace(); } } return null;}
寫(xiě)入
/** * 將數(shù)據(jù)寫(xiě)入文件中 * @param buffer 寫(xiě)入數(shù)據(jù) * @param fos 文件輸出流 */private void write(byte[] buffer, FileOutputStream fos) { //緩沖區(qū)OutputStream BufferedOutputStream bos = null; try { //初始化 bos = new BufferedOutputStream(fos); //寫(xiě)入 bos.write(buffer); //刷新緩沖區(qū) bos.flush(); } catch (IOException e) { e.printStackTrace(); } finally {//關(guān)閉流 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);//創(chuàng)建文件(getFilesDir()路徑在data/data/<包名>/files,需要root才能看到路徑)File file = new File(getFilesDir(), 'hui.mp3');boolean newFile = file.createNewFile();//寫(xiě)入if (bytes != null) { FileOutputStream fos = openFileOutput('hui.mp3', Context.MODE_PRIVATE); write(bytes, fos);}
該步驟為耗時(shí)操作,最好在io線程執(zhí)行
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 關(guān)于WPF WriteableBitmap類(lèi)直接操作像素點(diǎn)的問(wèn)題2. JavaScript前端中的偽類(lèi)元素before和after使用詳解3. ASP基礎(chǔ)入門(mén)第一篇(ASP技術(shù)簡(jiǎn)介)4. asp取整數(shù)mod 有小數(shù)的就自動(dòng)加15. 源碼分析MinimalApi是如何在Swagger中展示6. PHP laravel實(shí)現(xiàn)基本路由配置詳解7. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過(guò)程(親測(cè)可用)8. 熊海CMS代碼審計(jì)漏洞分析9. PHP JSAPI調(diào)支付API實(shí)現(xiàn)微信支付功能詳解10. 表單中Readonly和Disabled的區(qū)別詳解
