SDCard存储

当需要访问SD卡上的文件时,需要按照如下步骤进行

*调用Environment.getExternalStorageState()判读手机上是否插入SD卡(返回MEDIA_MOUNTED则表示已经插入)
*调用Environment.getExternalStorageDirectory()获取SD卡所在的目录
*使用文件IO流相关方法读写SD卡的内容
*在AndroidManifest.xml文件中添加与SD卡读写相关的权限
// 判断SDCard是否挂载
public static boolean isSDCardMounted() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return true;
    }
    return false;
}
// 获得SDCard的根目录 如/storage/sdcard/
public static String getSDCardBaseDir() {
    if (isSDCardMounted()) {
        File dir = Environment.getExternalStorageDirectory();
        return dir.getAbsolutePath();
    }
    return null;
}
// 获得SD卡的全部空间大小(单位:M)
public static long getSDCardSize() {
    if (isSDCardMounted()) {
        String dir = getSDCardBaseDir();
        StatFs statFs = new StatFs(dir); // StatFs是C语言引入过来的
        long blockCount = statFs.getBlockCountLong(); // 有多少块
        long blockSize = statFs.getBlockSizeLong(); // 每块有多大
        return blockCount * blockSize / 1024 / 1024;
    }
    return 0;
}
// 获取SDCard空闲空间的大小(单位:M) (有多少空间还没被占用的)
public static long getSDCardFreeSize() {
    if (isSDCardMounted()) {
        String dir = getSDCardBaseDir();
        StatFs statFs = new StatFs(dir); // StatFs是C语言引入过来的
        long freeBlockCount = statFs.getFreeBlocksLong(); // 空闲的块
        long blockSize = statFs.getBlockSizeLong(); // 每块有多大
        return freeBlockCount * blockSize / 1024 / 1024;
    }
    return 0;
}
// 获取SDCard可用空间的大小(单位:M) (有多少空间你可以使用的)
public static long getSDCardAvailSize() {
    if (isSDCardMounted()) {
        String dir = getSDCardBaseDir();
        StatFs statFs = new StatFs(dir); // StatFs是C语言引入过来的
        long availBlockCount = statFs.getAvailableBlocksLong(); // 可用的块
        long blockSize = statFs.getBlockSizeLong(); // 每块有多大
        return availBlockCount * blockSize / 1024 / 1024;
    }
    return 0;
}
// 往SDCard公有目录下保存文件 (九大公有目录中的一个,具体由type指定) /storage/sdcard/{type}
public static boolean saveData2SDCardPublicDir(byte[] data, String type, String filename) {
    if (isSDCardMounted()) {
        // 文件名:/storage/sdcard/Musics/111.txt
        // 文件名:getSDCardBaseDir()/{type}/{filename}
        String baseDir = getSDCardBaseDir();
        String file = baseDir + File.separator + type + "/" + filename;
        try {
            OutputStream os = new FileOutputStream(file);
            os.write(data);
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}
// 往SDCard的自定义目录中保存数据 /storage/sdcard/{dir}
public static boolean saveData2SDCardCustomDir(byte[] data, String dir, String filename) {
    if (isSDCardMounted()) {
        // /storage/sdcard/{dir}
        // getSDCardBaseDir()/{dir}/{filename}
        String baseDir = getSDCardBaseDir(); // SDCard目录
        String path = baseDir + "/" + dir; // SDCard中自定义的目录
        // 如果path不存在的话 需要创建目录
        File customPath = new File(path);
        if (!customPath.exists()) {
            customPath.mkdir();
        }
        String file = path + "/" + filename; // SDCard中自定义目录中的文件
        try {
            OutputStream os = new FileOutputStream(file);
            os.write(data);
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}
// :往SDCard的私有File目录下保存文件
// /storage/sdcard/Android/data/包名/files/{type}/{filename}
public static boolean saveData2SDCardPrivateFileDir(byte[] data, String type, String filename, Context context) {
    if (isSDCardMounted()) {
        // storage/sdcard/Android/data/包名/files/{type}/{filename}
        File path = context.getExternalFilesDir(type);
        if (!path.exists()) {
            path.mkdir();
        }
        String file = path.getAbsolutePath() + "/" + filename; // 文件路径
        try {
            OutputStream os = new FileOutputStream(file);
            os.write(data);
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}
// 往SDCard的私有Cache目录下保存文件 /storage/sdcard/Android/data/包名/cache/{filename}
public static boolean saveData2SDCardPrivateCacheDir(byte[] data, String filename, Context context) {
    if (isSDCardMounted()) {
        // storage/sdcard/Android/data/包名/cache/{filename}
        File path = context.getExternalCacheDir();
        if (!path.exists()) {
            path.mkdir();
        }
        String file = path.getAbsolutePath() + "/" + filename;
        try {
            OutputStream os = new FileOutputStream(file);
            os.write(data);
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}
// 往SDCard的私有Cache目录下保存图像 /storage/sdcard/Android/data/包名/cache/{filename}  xxx.png xxx.jpg
public static boolean saveBitmap2SDCardPrivateCacheDir(Bitmap bitmap, 
        String filename, Context context) {
    if(isSDCardMounted()) {
        // 路径/storage/sdcard/Android/data/包名/cache/{filename}
        File path = context.getExternalCacheDir();
        if(!path.exists()) {
            path.mkdir();
        }
        String file = path.getAbsolutePath() + "/" + filename; // bmp、jpg
        try {
            OutputStream os = new FileOutputStream(file);
            // 图片转换成byte[] 下面的代码代替os.write(...);
            // 判断到底是哪种图片的格式(jpg、png)
            if(filename.endsWith(".jpg") || filename.endsWith(".JPG")) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
            } else if (filename.endsWith(".png") || filename.endsWith(".PNG")) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os); 
            }
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    return false;
}
// 从SDCard读取指定文件 /storage/sdcard/{filePath}
public static byte[] loadFileFromSDCard(String filePath) {
    if(isSDCardMounted()) {
        // /storage/sdcard/{filePath}
        // getSDCardBaseDir()/{filePath}
        String path = getSDCardBaseDir();
        String file = path + "/" + filePath;
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int ret;
            while(true) {
                ret = is.read(buffer);
                if(ret < 0) {
                    break;
                }
                baos.write(buffer, 0, ret);
            }
            return baos.toByteArray(); // 返回字节数组
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return null;
}
// 从SDCard读取Bitmap并返回 /storage/sdcard/{filePath}
public static Bitmap loadBitmapFromSDCard(String filePath) {
    if(isSDCardMounted()) {
        // 由于传入的参数已经是全路径了 因此不需要加上getSDCardBaseDir()
        try {
            InputStream is = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int ret;
            while(true) {
                ret = is.read(buffer);
                if(ret < 0) {
                    break;
                }
                baos.write(buffer, 0, ret);
            }
            byte[] data = baos.toByteArray();
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return null;
}

 

posted @ 2016-03-30 20:04  嘉禾世兴  阅读(465)  评论(0编辑  收藏  举报