Android中文件的读写操作

来源:互联网 发布:centos系统升级 编辑:程序博客网 时间:2024/05/18 23:56

1.读取SD卡中的文件,转换为byte[]类型,代码如下:
private byte[] File2Bytes(File file) {
int byte_size = 1024;
byte[] b = new byte[byte_size];
try {
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(byte_size);
for (int length; (length = fileInputStream.read(b)) != -1;) {
outputStream.write(b, 0, length);
}
fileInputStream.close();
outputStream.close();
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
2.将YUV格式的数据保存成Jpeg格式,代码如下:
/**
* 解析YUV数据并保存
*
* @param data
* @param camera
*/
private void saveYUVData(byte[] data, String fileName) {
YuvImage yuvImg = new YuvImage(data, ImageFormat.NV21, 960, 720, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yuvImg.compressToJpeg(new Rect(0, 0, 960, 720), 100, baos);
byte[] jdata = baos.toByteArray();
// 摄影画像取得
Bitmap bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
BitmapUtils.storeImage(mActivity, bitmap, fileName.substring(0, fileName.lastIndexOf(“.”)), false);
}

3.Bitmap的保存操作,代码如下:
public static boolean storeImage(Context context, Bitmap bmp, String picType, boolean isRotate) {
// 拍照按下时更新本次操作的年月日时分秒
String takenTime_YYMMDD_HHMMSS = new SimpleDateFormat(DATA_FORMAT).format(new Date());
String path = PIC_ROOT_PATH + picType + “.jpg”;
File f = new File(path);
if (f != null && !f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if (isRotate) {
Matrix matrix = new Matrix();
matrix.reset();
matrix.postRotate(270);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
}
try {
FileOutputStream out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), f.getAbsolutePath(), f.getName(), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(“file://” + path)));
return true;
}

原创粉丝点击