码迷,mamicode.com
首页 > 移动开发 > 详细

Android 文件读写工具类

时间:2016-05-12 20:26:26      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

自己写的工具类,写的不好,慢慢修改。

记得加上权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

package com.sy.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by SY on 2016/5/9.
 * 文件读写工具类
 */
public class FileUtils {

    private Context context;
    private String SDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();//sd卡路径
    private static String SDState = Environment.getExternalStorageState();//SD卡状态

    public FileUtils(Context context) {
        this.context = context;
    }


    /**
     * 文件存储到/data/data/<packagename>/files/默认目录下
     *
     * @param fileName
     * @param bytes
     * @return
     */
    public boolean write2CacheFile(String fileName, byte[] bytes) {

        FileOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            out = context.openFileOutput(fileName, Context.MODE_PRIVATE);

            bos = new BufferedOutputStream(out);
            bos.write(bytes);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return false;
    }


    /**
     * 向SD卡里写字节
     *
     * @param path 文件夹目录
     * @param file 文件名
     * @param data 写入的字节数组
     * @return
     */
    public static boolean writeBytes(String path, String file, byte[] data) {
        FileOutputStream fos = null;
        try {
            // 拥有足够的容量
            if (data.length < getSDFreeSize()) {
                createDirectoryIfNotExist(path);
                createFileIfNotExist(path + file);

                fos = new FileOutputStream(path + File.separator + file);
                fos.write(data);
                fos.flush();
                return true;
            }
        }catch (Exception e){
            Log.e("writeBytes", e.getMessage());
        }finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    }

    /**
     * 从SD卡里读取字节数组
     *
     * @param path     目录
     * @param fileName 文件名
     * @return 返回字节数组,文件不存在返回null
     */
    public static byte[] readBytes(String path, String fileName) {
        File file = new File(path + File.separator + fileName);
        if (!file.exists()) {
            return null;
        }
        InputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将一个字节流写入到SD卡文件
     *
     * @param path     目录路径
     * @param fileName 文件名
     * @param input    字节流
     * @return
     */

    public static Boolean write2SDFromInput(String path, String fileName, InputStream input) {
        File file = null;
        OutputStream output = null;
        try {
            int size = input.available();
            // 拥有足够的容量
            if (size < getSDFreeSize()) {
                createDirectoryIfNotExist(path);
                createFileIfNotExist(path + File.separator + fileName);
                file = new File(path + File.separator + fileName);
                output = new BufferedOutputStream(new FileOutputStream(file));
                byte buffer[] = new byte[1024];
                int temp;
                while ((temp = input.read(buffer)) != -1) {
                    output.write(buffer, 0, temp);
                }
                output.flush();
                return true;

            }
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


    /**
     * 判断SD卡是否存在
     *
     * @ return
     */
    private static boolean SDCardisExist() {
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }

    /**
     * 获取SD卡剩余容量大小(单位Byte)
     *
     * @return
     */
    public static long getSDFreeSize() {
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
//        return (freeBlocks * blockSize) / 1024 / 1024; //单位MB
    }

    /**
     * 获取SD卡总容量大小(单位Byte)
     *
     * @return
     */
    public static long getSDAllSize() {
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //获取所有数据块数
        long allBlocks = sf.getBlockCount();
        //返回SD卡大小
        return allBlocks * blockSize; //单位Byte
        //return (allBlocks * blockSize)/1024; //单位KB
//        return (allBlocks * blockSize) / 1024 / 1024; //单位MB
    }

    /**
     * 如果目录不存在,就创建目录
     *
     * @param path 目录
     * @return
     */
    public static boolean createDirectoryIfNotExist(String path) {
        File file = new File(path);
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            return file.mkdirs();
        } else {
            Log.e("目录", "目录存在!");
            return false;
        }

    }

    /**
     * 如果文件不存在,就创建文件
     * @param path 文件路径
     * @return
     */
    public static boolean createFileIfNotExist(String path) {
        File file = new File(path);
        try {
            if (!file.exists()) {
                return file.createNewFile();
            } else {
                Log.e("文件", "文件存在!");
                return false;
            }
        } catch (Exception e) {
            Log.e("error", e.getMessage());
            return false;
        }
    }
}

Android 文件读写工具类

标签:

原文地址:http://blog.csdn.net/mouse12138/article/details/51352692

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!