概述
敲android代碼也快半年了,大神都說(shuō)好記性不如爛筆頭,把自己看的一些東西也記錄下來(lái),本次學(xué)習(xí)android File操作這一塊。
File
打開(kāi)文件夾
public File openFileDirectory(final String path) {
Log.i(TAG, "openFileDirectory: string = " + path);
if (path == null)
return null;
File file = new File(path);
if (!file.exists()) {
if (file.mkdir())
Log.e(TAG, "openFileDirectory: Dir create success" );
}
Log.i(TAG, "openFileDirectory: dir absolutepath = " + file.getAbsolutePath());
openFile(file.getAbsolutePath(),"qian.txt");
return file;
}
保存字符串到txt 文檔中
public File openFile(final String path,final String name) {
if (path == null || name == null) {
Log.e(TAG, "openFile path or name is null" );
}
File mfile = new File(path,name); // 打開(kāi)文件,打開(kāi)后并不會(huì)保存,調(diào)用Filewrite才會(huì)保存
Log.e(TAG, "openFile: ");
writeStrWithStream(mfile,"facai zheng daqian");
return mfile;
}
public void writeStrWithStream(final File file,final String str) {
FileWriter fw = null;
try {
fw = new FileWriter(file);
fw.write(str);
fw.write("\r\n"); //換行
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
保存圖片NV21
private void SaveNV21Bitmap(ByteBuffer fram) {
byte[] data = new byte[fram.capacity()];
fram.get(data);
File pictureFile = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "UsbCamera" + ".jpg");
try {
FileOutputStream filecon = new FileOutputStream(pictureFile);
YuvImage image = new YuvImage(data, ImageFormat.NV21, 640, 480, null); //將NV21 data保存成YuvImage
//圖像壓縮
image.compressToJpeg(
new Rect(0, 0, image.getWidth(), image.getHeight()),
70, filecon); // 將NV21格式圖片,以質(zhì)量70壓縮成Jpeg,并得到JPEG數(shù)據(jù)流
}catch (IOException e)
{
e.printStackTrace();
}
}
Bitmap保存圖片
public void saveByteToImage(final byte[] data,File file) {
if (data == null || file == null)
return;
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,85,fos);
}catch (FileNotFoundException e){s
Log.e(TAG, "saveByteToImage: " + e.getMessage() );
}
}