Android入门——数据存储之IO文件流操作小结

引言

Android数据存储基本可以分为四种:数据库(SQLite、其他远程网络服务器)、轻量级的本地存储SharedPreference、内容提供器ContentProvider数据共享、文件File IO流。前期的文章总结了前面三种的基本语法,这一篇迟来的文件IO流的总结,主要就是一些常用方法的总结。

一、Bitmap与InputStream的转化

 /**
 * 位图转为InputSteam
 * @param bitmap
 * @return
 */
public static InputStream bitmap2InputStream(Bitmap bitmap) {
    ByteArrayOutputStream byteArrOutStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrOutStream);
    InputStream inStream = new ByteArrayInputStream(byteArrOutStream.toByteArray());
    return inStream;
}

// 将InputStream转换成Bitmap
public static Bitmap inputStream2Bitmap(InputStream inStream) {
    //return BitmapFactory.decodeStream(inStream);
     BitmapFactory.Options options=new BitmapFactory.Options();
     options.inJustDecodeBounds = false;
     options.inSampleSize = 10;   //width,hight都设为原来的十分一,If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.
     Bitmap btp =BitmapFactory.decodeStream(inStream,null,options);
     return btp;
}

二、Bitmap与Drawable的转化

/**
* Drawable转换成Bitmap
*/
public static Bitmap drawable2Bitmap(Drawable drawable) {
   Bitmap bitmap = Bitmap
           .createBitmap(
                   drawable.getIntrinsicWidth(),
                   drawable.getIntrinsicHeight(),
                   drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                           : Bitmap.Config.RGB_565);
   Canvas canvas = new Canvas(bitmap);
   drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
           drawable.getIntrinsicHeight());
   drawable.draw(canvas);
   return bitmap;
}

// Bitmap转换成Drawable
public static Drawable bitmap2Drawable(Bitmap bitmap) {
   BitmapDrawable bd = new BitmapDrawable(bitmap);
   Drawable d = (Drawable) bd;
   return d;
}

四、Bitmap转为byte[]

/**
*  Bitmap转成byte[]
*/
public static byte[] bitmap2Bytes(Bitmap bitmap) {
    ByteArrayOutputStream byteArrOutStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrOutStream);
    return byteArrOutStream.toByteArray();
}

/**
 *  byte[]转换成Bitmap  
 */
public static Bitmap bytes2Bitmap(byte[] bytes) {
    if (bytes.length != 0) {
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }
    return null;
}

五、以最省内存的方式和最大程度避免OOM读取本地资源图片

/**
* 以最省内存的方式读取本地资源的图片
* @param context
* @param resId
* @return
*/
public static Bitmap readBitMap(@NonNul Context context, @NonNul int resId){
   BitmapFactory.Options opt = new BitmapFactory.Options();
   opt.inPreferredConfig = Bitmap.Config.RGB_565;
   opt.inInputShareable = true;
   //获取资源图片
   InputStream is = context.getResources().openRawResource(resId);
   return BitmapFactory.decodeStream(is,null,opt);
}

六、保存输入流到指定路径

/**
     *
     * @param inStream  文件的输入流
     * @param savePath  保存该文件的路径,包括所有父目录
     * @param fileName  文件的名称
     * @return
     */
    public static boolean saveFile(InputStream inStream, String savePath, String fileName) {
        boolean result = false;
        //File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"FKEZOpenSDK/CapturePicture/20161028/1522483305.jpg");
        File file=new File(savePath,fileName);
        FileOutputStream fileOutputStream;//存入SDCard的流
        ByteArrayOutputStream outStream;
        try {
            //首先判断文件是否存在
            if(!file.exists()){
                //再判断文件的父目录是否存在
                if(file.getParentFile() != null){
                    file.getParentFile().mkdirs();//父目录不存在则创建
                }
                file.createNewFile();//创建文件
            }
            //把流写入到文件中
            fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[10];
            outStream = new ByteArrayOutputStream();
            int len;
            while((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] bs = outStream.toByteArray();
            fileOutputStream.write(bs);
            fileOutputStream.flush();
            fileOutputStream.close();
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        }
        return result;
    }

七、获取当前路径下的可用空间

/**
 * 获取当前路径剩余空间的大小以字节为单位
 * @return
 */
public static long  getSDCardRemainSize(String path){
    //StatFs statfs = new StatFs(Environment.getExternalStorageDirectory().getPath());
    StatFs statfs = new StatFs(path);
    long blockSize = statfs.getBlockSizeLong();
    long availableBlocks = statfs.getAvailableBlocksLong();
    return availableBlocks * blockSize;
}

八、获取SDCard的路径

/**
     * 获取SDCard的保存路径
     * @return
     */
    public static String  getSDCardPath(){
        return Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";
    }

待续…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CrazyMo_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值