2、外部存储,sdcard
案例一:外部存储时一般通用的工具类
public class SDCardUtils {
// 判断SDCard是否挂载,true,挂载,false,未挂载
// Environment.MEDIA_MOUNTED,表示sdCard已经挂载
// Environment.getExternalStorageState(),获得当前sdCard的挂载状态
public static boolean isMounted() {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
return true;
}
return false;
}
// 获得SDCard 的路径
public static String getSDCardPath() {
if (isMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
// 获得scCard的大小
public static long getSize() {
if (isMounted()) {
// StatFs,用来计算文件系统存储空间大小的工具类
StatFs stat = new StatFs(getSDCardPath());
// 获得块的数量
// int count = stat.getBlockCount();
long count = stat.getBlockCountLong();
// 获得每块的大小
// int size = stat.getBlockSize();
long size = stat.getBlockSizeLong();
return count * size / 1024 / 1024;
}
return 0;
}
// 获得sdcard可用大小
public static long getAvailableSize() {
if (isMounted()) {
StatFs stat = new StatFs(getSDCardPath());
// 可用的块数
long availCount = stat.getAvailableBlocksLong();
// 块的大小
long size = stat.getBlockSizeLong();
return availCount * size / 1024 / 1024;
}
return 0;
}
// 将文件保存到sdCard
// data,保存的数据
// dir,保存的路径
// fileName,保存的文件名
public static boolean saveDataIntoSDCard(byte[] data, String dir,
String fileName) {
if (isMounted()) {
// 先判断存储的路径dir是否存在(创建),如果不存在,先创建
String path = getSDCardPath() + File.separator + dir;
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
// 如果存在,进行读写操作
file = new File(path + File.separator + fileName);
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bos != null)
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 读取sdcard的数据
public static byte[] getDataFromSDCard(String dir, String fileName) {
if (isMounted()) {
String path = getSDCardPath() + File.separator + dir
+ File.separator + fileName;
File file = new File(path);
if (file.exists()) {
ByteArrayOutputStream baos = null;
BufferedInputStream bis = null;
try {
baos = new ByteArrayOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[1024 * 8];
int n = 0;
while ((n = bis.read(b)) != -1) {
baos.write(b, 0, n);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
// 根据具体的类型获得公共路径
public static String getPublicPath(String type) {
if (isMounted()) {
return Environment.getExternalStoragePublicDirectory(type)
.getAbsolutePath();
}
return null;
}
// 保存公共路径下
public static boolean saveDataIntoSDCardPublic(byte[] data, String type,
String fileName) {
if (isMounted()) {
File file = new File(getPublicPath(type));
if (!file.exists()) {
file.mkdirs();
}
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data, 0, data.length);
bos.flush();
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (bos != null)
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
// 根据上下文,以及路径的类型,返回私有的路径名
public static String getPrivatePath(Context context, String type) {
if (isMounted()) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
return null;
}
// 保存到私有路径下
public static boolean saveDataIntoSDCardPrivate(byte[] data,
Context context, String type, String fileName) {
if (isMounted()) {
File file = new File(getPrivatePath(context, type));
if (!file.exists()) {
file.mkdirs();
}
BufferedOutputStream bos = null;
try {
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 {
try {
if (bos != null)
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
}
案例二:文件浏览器
acctivity中:
public class MainActivity extends Activity {
private TextView tvCurrent, tvState;
private ListView lv;
private FileAdapter adapter;
private boolean flag;
// 存储数据:包括文件名(文件夹名) 和 图片
private List<Map<String, String>> data = new ArrayList<Map<String, String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// 使用工具类,获得LIstView中显示的数据
if (SDCardUtils.isMounted()) {
flag = SDCardUtils.listDirectory(new File(SDCardUtils.getSDCardPat()), data);
}
// 设置当前路径
tvCurrent.setText(SDCardUtils.getSDCardPath());
// 显示存储状态
long size = SDCardUtils.getSize();
long availSize = SDCardUtils.getAvailableSize();
tvState.setText("总容量:" + size + ",可用容量:" + availSize);
// 创建并设置适配器
adapter = new FileAdapter(this, data);
lv.setAdapter(adapter);
}
private void initView() {
// TODO Auto-generated method stub
tvCurrent = (TextView) findViewById(R.id.tv_current);
tvState = (TextView) findViewById(R.id.tv_state);
lv = (ListView) findViewById(R.id.lv);
// @android:id/empty",如果是ListActivity,自动添加
// 如果是普通的Activity,使用该方法添加空视图
lv.setEmptyView(findViewById(android.R.id.empty));
// Listview绑定单击事件,点击,进入下一级
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// 组织下一级的路径名,有可能是文件名
String clickPath = tvCurrent.getText().toString()
+ File.separator + data.get(position).get("name");
File file = new File(clickPath);
// 判断该路径是否为文件夹
if (file.isDirectory()) {
boolean b = SDCardUtils.listDirectory(file, data);
if (b) {
adapter.notifyDataSetChanged();
tvCurrent.setText(clickPath);
} else {
Toast.makeText(getApplicationContext(), "文件夹不可访问", 1)
.show();
}
} else {
// 不同类型的文件使用隐式意图打开
}
}
});
}
// 返回上一级按钮
public void back(View v) {
// 获得当前路径
String current = tvCurrent.getText().toString();
// 判断是否到达根目录
if (current.equals(SDCardUtils.getSDCardPath())) {
Toast.makeText(this, "已经到达根目录", 1).show();
} else {
File file = new File(current);
// 获得父目录,上一级
File parentFile = file.getParentFile();
// 根据上一级目录,获得内容,并显示
SDCardUtils.listDirectory(parentFile, data);
adapter.notifyDataSetChanged();
tvCurrent.setText(parentFile.getAbsolutePath());
}
}
}
适配器:
public class FileAdapter extends BaseAdapter {
private Context context;
private List<Map<String, String>> data;
public FileAdapter(Context context, List<Map<String, String>> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item,
null);
holder.iv = (ImageView) convertView.findViewById(R.id.iv);
holder.tv = (TextView) convertView.findViewById(R.id.tv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Map<String, String> map = data.get(position);
holder.tv.setText(map.get("name").toString());
String type = map.get("type").toString();
int resId = 0;
if ("dir".equals(type)) {
resId = R.drawable.greenpng_016;
} else if ("file".equals(type)) {
resId = R.drawable.greenpng_011;
}
holder.iv.setImageResource(resId);
return convertView;
}
class ViewHolder {
TextView tv;
ImageView iv;
}
}
外部存储的工具类中再添加一个方法:
// 遍历某个文件夹下的内容
// file:文件夹名
// data:数据的集合
public static boolean listDirectory(File file,
List<Map<String, String>> data) {
// 遍历文件夹下的内容
File[] files = file.listFiles();
if (files == null) {// 文件夹为空
return false;
}
// 处理文件夹不为空
// 清空之前存储的数据
data.clear();
for (File f : files) {
Map<String, String> map = new HashMap<String, String>();
String fileName = f.getName();// 获得文件名
String type = "";// 类型,表示文件夹或文件
if (f.isDirectory()) {
type = "dir";
} else if (f.isFile()) {
type = "file";
}
map.put("name", fileName);
map.put("type", type);
data.add(map);
}
return true;
}
布局文件中和菜单中的省略。