版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21983189/article/details/65635771
开发中我们经常会遇到数据的拷贝,通常的拷贝方式都是以下这种:
public boolean copyDataToSD(Context context, String fileName, File strOutFile) {
try {
OutputStream myOutput = new FileOutputStream(strOutFile);
InputStream myInput = context.getAssets().open(fileName);
byte[] buffer = new byte[1024];
int length = myInput.read(buffer);
while (length > 0) {
myOutput.write(buffer, 0, length);
length = myInput.read(buffer);
}
myOutput.close();
myInput.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
这种方式,有时候在android有些设备中假如遇到大文件从apk中拷贝出去的话,就会失败,原因和系统的版本与兼容性有关。所以,我们在将assets或者raw目录中的文件拷贝出去时,最佳的拷贝方式是这样的(不限大小哦):
/**
* @param context 上下文
* @param fileName 要从assets中拷贝的文件名
* @param outFileName 的目标文件目录
*/
public void CopyDataToSdcard(Context context, String fileName, String outFileName) {
try {
InputStream is = context.getResources().getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(new File(outFileName));
fos.write(buffer);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
显然,这种方式不论在效率上,兼容性上要高很多!