Android获取存储卡路径

public class TFCardInfo {

	private static TFCardInfo instance;

	public String mTFCardName = null;
	public String mTFCardPath = null;
	public String mSDCardPath = null;

	public static synchronized TFCardInfo getInstance() {

		if (instance == null) {
			instance = new TFCardInfo();
		}

		return instance;
	}

	/**
	 * 功  能:得到TF卡的名字和路径,赋给类变量<br>
	 * 时  间:2014年12月25日 上午10:31:26<br>
	 * 注  意:<br>
	 * 1.要判断磁盘是否准备好<br>
	 * 
	 * @param context
	 */
	public void GetTFCardPathName(Context context) {
		/** 要排除的目录名称 */
		String[] excludeDirs = { "media_rw", "asec", "cd-rom", "obb", "sdcard", "secure", "shell", "usbotg",
				"usb_storage", "UsbDrive" };

		// 获取扩展存储设备的文件目录
		File adbFile = new File("/mnt");
		File[] tempList = adbFile.listFiles();

		boolean isFind = false;
		for (File curFile : tempList) {
			isFind = false;

			if (curFile.isDirectory()) {

				for (String dirName : excludeDirs) {// 遍历筛选目录
					if (curFile.getName().equals(dirName)) {
						isFind = true;
						break;
					}
				}
				if (isFind == false) {// 如果筛选项里没有的话,说明已经找到
					mTFCardName = curFile.getName();
					mTFCardPath = curFile.getAbsolutePath();
					mTFCardPath = "/mnt/" + mTFCardName + "/";
					break;
				}
			}
		}
	}

	/**
	 * 功  能:判断TF卡是否存在<br>
	 * 时  间:2014年12月19日 上午9:50:10<br>
	 * 注  意:<br>
	 * 
	 * @TODO:<br>
	 * @param context
	 * @return <br>
	 */
	public Boolean CheckTFCardExists(Context context) {

		if (mTFCardPath == null) {
			// 防止先调用了这个函数
			GetTFCardPathName(context);
		}
		if (mTFCardPath == null) {
			// 路径不存在,则要返回
			return false;
		}

		// 下面通过创建一个文件来判断是否存在tfcard
		String tempfilepathnameString = mTFCardPath + "checktfcard.txt";
		File file = new File(tempfilepathnameString);
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (file.exists()) {
			file.delete();// 删除此测试文件
			return true;
		}

		return false;

	}

	/**
	 * 功  能:获取SD卡路径<br>
	 * 时  间:2015年4月14日 下午5:49:43<br>
	 * 注  意:<br>
	 * 
	 * @return
	 */
	public String getSDPath() {

		boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			File file = Environment.getExternalStorageDirectory();// 获取跟目录
			mSDCardPath = file.toString();
		}
		return mSDCardPath;

	}

}

使用

TFCardInfo tfCardInfo = TFCardInfo.getInstance();
tfCardInfo.CheckTFCardExists(this);
tv.setText("SD卡路径" + tfCardInfo.getSDPath() + "tf名称" + tfCardInfo.mTFCardName + "TF路径" + tfCardInfo.mTFCardPath);

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部