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

Android-SD卡的读写

2015-06-23 22:06 316 查看
步骤1、在程序中使用sdcard进行存储,我们必须要在AndroidManifset.xml文件进行下面的权限设置:

<!-- SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 向SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

步骤2、了解Environment类的几个常用的静态方法

1: getDataDirectory() 获取到Android中的data数据目录(sd卡中的data文件夹)

2:getDownloadCacheDirectory() 获取到下载的缓存目录(sd卡中的download文件夹)
3:getExternalStorageDirectory() 获取到外部存储的目录 一般指SDcard(/storage/sdcard0)
4:getExternalStorageState() 获取外部设置的当前状态 一般指SDcard,比较常用的应该是 MEDIA_MOUNTED(SDcard存在并且可以进行读写)还有其他的一些状态,可以在文档中进行查找。
5:getRootDirectory() 获取到Android Root路径

步骤3、具体读写方式:

(1)判断SD卡是否存在

/**
	 * 判断SDCard是否存在 [当没有外挂SD卡时,内置ROM也被识别为存在sd卡]
	 * 
	 * @return
	 */
	public static boolean isSdCardExist() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}


(2)获取SD卡根目录

/**
	 * 获取SD卡根目录路径
	 * 
	 * @return
	 */
	public static String getSdCardPath() {
		boolean exist = isSdCardExist();
		String sdpath = "";
		if (exist) {
			sdpath = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
		} else {
			sdpath = "不适用";
		}
		return sdpath;

	}


(3)获取默认的文件存放路径

/**
	 * 获取默认的文件路径
	 * 
	 * @return
	 */
	public static String getDefaultFilePath() {
		String filepath = "";
		File file = new File(Environment.getExternalStorageDirectory(),
				"abc.txt");
		if (file.exists()) {
			filepath = file.getAbsolutePath();
		} else {
			filepath = "不适用";
		}
		return filepath;
	}


(4)读取文件

try {
    		File file = new File(Environment.getExternalStorageDirectory(),
    				"test.txt");
            FileInputStream is = new FileInputStream(file);
            byte[] b = new byte[inputStream.available()];
            is.read(b);
            String result = new String(b);
            System.out.println("读取成功:"+result);
        } catch (Exception e) {
        	e.printStackTrace();
        }


(5)写入文件

try {
			File file = new File(Environment.getExternalStorageDirectory(),
					DEFAULT_FILENAME);
	         FileOutputStream fos = new FileOutputStream(file);
	         String info = "I am a chinanese!";
             fos.write(info.getBytes());
             fos.close();
			System.out.println("写入成功:");
		} catch (Exception e) {
			e.printStackTrace();
		}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: