读取
private byte[] read(InputStream is) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
byte[] b = new byte[1024];
bis = new BufferedInputStream(is);
baos = new ByteArrayOutputStream();
int length;
while ((length = bis.read(b)) != -1) {
baos.write(b, 0, 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;
}
写入
private void write(byte[] buffer, FileOutputStream fos) {
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);
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线程执行