Android File

概述

敲android代码也快半年了,大神都说好记性不如烂笔头,把自己看的一些东西也记录下来,本次学习android File操作这一块。

File

打开文件夹

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); // 打开文件,打开后并不会保存,调用Filewrite才会保存
        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格式图片,以质量70压缩成Jpeg,并得到JPEG数据流

            }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() );
        }
}

你可能感兴趣的:(Android File)