---
title: "操作内存卡的常用代码"
author: "AndLi"
date: "2011-09-28T08:03:37Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-09-28T08:09:47Z"
id: 1181994
url: "https://andli.iteye.com/blog/1181994"
---

1.操作权限

&lt;!-- SD卡写入 --&gt;

&lt;uses-permission android:name=*"android.permission.WRITE\_EXTERNAL\_STORAGE"* /&gt;

&lt;uses-permission android:name=*"android.permission.DELETE\_CACHE\_FILES"* /&gt;

 

```

```

```

```

 

 

 

2.获取文件保存路径

```
// 获取保存路径
	public File getFilePath() {
		File filePath = null;
		//判断SD卡存在与否
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/A_Test/test/");
			if (!filePath.isDirectory()) {//判断文件存在与否，不存在就创建
				filePath.mkdirs();
			}
		} else {
			Toast.makeText(Main.this, "存储卡不存在，请插入卡!", 3000).show();
		}
		return filePath;
	}
```

  

3.获取图片保存路径

 

```
// 获得SD的路径
	public String getSDPath() {
		File sdPath = null;
		if (Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) { // sd卡存在
			sdPath = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ File.separator + "mobileoa" + File.separator + "photo");// 获得路径
			// sdPath = new File(Environment.getExternalStorageDirectory()
			// .getAbsolutePath());// 获得根路径
		}
		return sdPath != null ? sdPath.toString() : "内存卡不存在！";
	}

	// 获得SDCard下图片的路径
	private List<String> getSDCard() {
		imagePaths = new ArrayList<String>();
		try {
			File file = new File(getSDPath());
			File[] files = file.listFiles();
			for (File theFile : files) {
				if (isImageFile(theFile.getPath())) {
					imagePaths.add(theFile.getPath());
				}
			}
		} catch (Exception e) {
			return imagePaths;
		}
		return imagePaths;
	}

	// 判断是否是图片文件
	private boolean isImageFile(String fileName) {
		String extension = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length()).toLowerCase();
		if (extension.equals("jpg") || extension.equals("png")
				|| extension.equals("gif") || extension.equals("jpeg")
				|| extension.equals("bmp")) {
			return true;
		}
		return false;
	}
```