android開發(fā)實現(xiàn)文件讀寫
更新時間:2020年07月28日 09:14:14 作者:jChenys
這篇文章主要為大家詳細介紹了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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android進程通信之Messenger和AIDL使用詳解
本篇文章主要介紹了Android進程通信之Messenger和AIDL使用詳解,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
Android開發(fā)之BroadcastReceiver用法實例分析
這篇文章主要介紹了Android開發(fā)之BroadcastReceiver用法,實例分析了Android中廣播的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05
GridView基于pulltorefresh實現(xiàn)下拉刷新 上拉加載更多功能(推薦)
原理和listview一樣 ,都是重寫Android原生控件。下面小編通過實例代碼給大家分享GridView基于pulltorefresh實現(xiàn)下拉刷新 上拉加載更多功能,非常不錯,一起看看吧2016-11-11
13問13答全面學(xué)習(xí)Android View繪制
這篇文章主要為大家詳細介紹了Android View繪制,13問13答幫助大家全面學(xué)習(xí)Android View繪制,感興趣的小伙伴們可以參考一下2016-03-03
android判斷手機是否安裝地圖應(yīng)用實現(xiàn)跳轉(zhuǎn)到該地圖應(yīng)用
這篇文章主要給大家介紹了android如何判斷手機是否安裝地圖應(yīng)用,并實現(xiàn)跳轉(zhuǎn)到該地圖應(yīng)用的方法,需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。2017-01-01

