android開發(fā)實現(xiàn)文件讀寫
本文實例為大家分享了android實現(xiàn)文件讀寫的具體代碼,供大家參考,具體內(nèi)容如下
讀取
/** * 文件讀取 * @param is 文件的輸入流 * @return 返回文件數(shù)組 */ private byte[] read(InputStream is) { //緩沖區(qū)inputStream BufferedInputStream bis = null; //用于存儲數(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()會將讀到的數(shù)據(jù)添加到b數(shù)組 //將數(shù)組寫入到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; }
寫入
/** * 將數(shù)據(jù)寫入文件中 * @param buffer 寫入數(shù)據(jù) * @param fos 文件輸出流 */ private void write(byte[] buffer, FileOutputStream fos) { //緩沖區(qū)OutputStream BufferedOutputStream bos = null; try { //初始化 bos = new BufferedOutputStream(fos); //寫入 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(); //寫入 if (bytes != null) { FileOutputStream fos = openFileOutput("hui.mp3", Context.MODE_PRIVATE); write(bytes, fos); }
該步驟為耗時操作,最好在io線程執(zhí)行
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android基于zxing的二維碼(網(wǎng)格)掃描 仿支付寶網(wǎng)格掃描
這篇文章主要為大家詳細介紹了Android基于zxing的二維碼網(wǎng)格掃描,仿支付寶網(wǎng)格掃描,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03Android使用Retrofit實現(xiàn)自定義Converter解析接口流程詳解
Retrofit是一個RESTful的HTTP網(wǎng)絡(luò)請求框架的封裝,網(wǎng)絡(luò)請求的工作本質(zhì)上是OkHttp完成,而Retrofit僅負責網(wǎng)絡(luò)請求接口的封裝2023-03-03詳解AndroidStudio中代碼重構(gòu)菜單Refactor功能
這篇文章主要介紹了AndroidStudio中代碼重構(gòu)菜單Refactor功能詳解,本文通過代碼演示,功能截圖來詳細說明as為大名重構(gòu)提供的各項功能,需要的朋友可以參考下2019-11-11Android中invalidate()和postInvalidate() 的區(qū)別及使用方法
Android中實現(xiàn)view的更新有兩組方法,一組是invalidate,另一組是postInvalidate,其中前者是在UI線程自身中使用,而后者在非UI線程中使用。本文給大家介紹Android中invalidate()和postInvalidate() 的區(qū)別及使用方法,感興趣的朋友一起學習吧2016-05-05Android、iOS和Windows Phone中的推送技術(shù)詳解
這篇文章主要介紹了Android、iOS和Windows Phone中的推送技術(shù)詳解,推送技術(shù)的實現(xiàn)通常會使用服務(wù)端向客戶端推送消息的方式,也就是說客戶端通過用戶名、Key等ID注冊到服務(wù)端后,在服務(wù)端就可以將消息向所有活動的客戶端發(fā)送,需要的朋友可以參考下2015-01-01Android開源項目PullToRefresh下拉刷新功能詳解
這篇文章主要為大家詳細介紹了Android開源項目PullToRefresh下拉刷新功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09