您的位置:首页 > 移动开发 > Android开发

Android开发之SDCardUtils工具类。java工具详细代码,附源代码。判断SD卡是否挂载等功能

2016-05-31 00:00 921 查看
package com.xiaobing.zhbj.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;
/**
*
*
* @author :QQ:986945193
*
* @新浪微博 :http://weibo.com/mcxiaobing
*
* @version V1.0正式版
*
* SDCard工具类
*
*/
public class SDCardUtils {
/**
* 判断SD卡是否挂载
*
* @return
*/
public static boolean isMounted() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}

// 得到SD卡的根路径
public static String getSDPath() {

if (isMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}

// 将文件保存到SD卡中
public static boolean saveFileIntoSDCard(byte[] data, String path,
String fileName) {

if (isMounted()) {

BufferedOutputStream bos = null;
try {
String filePath = getSDPath() + File.separator + path;
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}

bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data, 0, data.length);
bos.flush();

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

}

return false;
}

// 从SD卡中取出存储的文件
public static byte[] getFileFromSDCard(String filePath) {

if (isMounted()) {
File file = new File(filePath);
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
if (file.exists()) {
try {
baos = new ByteArrayOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int len = 0;
byte[] buffer = new byte[1024 * 8];
while ((len = bis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
baos.flush();
}

return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
}

return null;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐