android 开发-文件存储之读写sdcard

  android提供对可移除的外部存储进行文件存储。在对外部sdcard进行调用的时候首先要调用Environment.getExternalStorageState()检查sdcard的可用状态。通过Environment.getExternalStorageDirectory()得到Sdcard的路径。文件写入外部存储需要添加对sdcard的授权

  <!-- 写sdcard需要添加写sdcard的授权 -->
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  boolean mExternalStorageAvailable = false;
  boolean mExternalStorageWriteable = false;
  String state = Environment.getExternalStorageState();

  if (Environment.MEDIA_MOUNTED.equals(state)) {
      // We can read and write the media
      mExternalStorageAvailable = mExternalStorageWriteable = true;
  } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
      // We can only read the media
      mExternalStorageAvailable = true;
      mExternalStorageWriteable = false;
  } else {
      // Something else is wrong. It may be one of many other states, but all we need
      //  to know is we can neither read nor write
      mExternalStorageAvailable = mExternalStorageWriteable = false;
  }
android学习过程中的示例如下:
  文件读写工具类:
  
 1 package com.example.android_data_storage_sdcard.file;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.File;
 5 import java.io.FileInputStream;
 6 import java.io.FileNotFoundException;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 
10 import android.os.Environment;
11 import android.util.Log;
12 /**
13  * @author xiaowu
14  * @note  文件存储之外部存储(sdcard存储)。
15  *         外部存储不需要context        
16  */
17 public class FileUitls {
18     private final String TAG = "FileUtil";
19 
20     /**
21      * 保存文件至外部存储的SD卡
22      * @param fileName
23      * @param mode
24      * @param data
25      * @return 是否存储内容到sdcard成功
26      */
27     public boolean saveFileToSdcard(String fileName,  byte[] data) {
28         boolean flag = false;
29         // 判断sdcard的状态
30         String state = Environment.getExternalStorageState();
31         // 获取sdcard的根目录 /mnt/sdcard/...
32         File root = Environment.getExternalStorageDirectory();
33         FileOutputStream outputStream = null;
34         // Environment.MEDIA_MOUNTED表示SD卡挂载在手机上并可以读写
35         if (Environment.MEDIA_MOUNTED.equals(state)) {
36             // 在sdcard的根目录下创建文件
37             File file = new File(root, fileName);
38             try {
39                 outputStream = new FileOutputStream(file);
40                 outputStream.write(data, 0, data.length);
41                 flag = true ;
42             } catch (FileNotFoundException e) {
43                 Log.i(TAG, "文件未找到异常!");
44             } catch (Exception e) {
45                 Log.i(TAG, "写文件发生异常");
46             } finally {
47                 if (outputStream != null) {
48                     try {
49                         outputStream.close();
50                     } catch (IOException e) {
51                         Log.i(TAG, "关闭IO流发生异常!");
52                     }
53                 }
54             }
55         }
56         return flag;
57     }
58     /**
59      * 从sdcard中读文件
60      * @param fileName
61      * @return 文件内容
62      */
63     public String  readFromSdcard(String fileName){
64         String  str = "" ;
65         FileInputStream inputStream = null;
66         String state = Environment.getExternalStorageState();
67         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
68         try {
69             if (Environment.MEDIA_MOUNTED.equals(state)) {
70                 //获取Sdcard路径
71                 File root = Environment.getExternalStorageDirectory();
72                 File file = new File(root.getAbsolutePath(),fileName);
73                 if(file.exists()){
74                     inputStream = new FileInputStream(file);
75                     int len = 0 ;
76                     byte[] data = new byte[1024];
77                     while ((len = inputStream.read(data)) != -1) {
78                         byteArrayOutputStream.write(data, 0, len);
79                     }
80                     return new String(byteArrayOutputStream.toByteArray());
81                 }
82             }
83         } catch (Exception e) {
84             Log.i(TAG, "文件读取异常!");
85         }finally{
86             if(inputStream != null){
87                 try {
88                     inputStream.close();
89                 } catch (IOException e) {
90                     Log.i(TAG, "关闭流异常!");
91                 }
92             }
93         }
94         return str ;
95     }
96 }

  Junit单元测试类:

  单元测试类必须继承自AndroidTestCase,并在资源清单文件中添加单元测试包  <uses-library android:name="android.test.runner"/>,并添加单元测试目标包

  <!-- 引入单元测试目标包 -->
  <instrumentation
    android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.example.android_data_storage_sdcard" >
  </instrumentation>

 1 package com.example.android_data_storage_sdcard;
 2 
 3 import android.test.AndroidTestCase;
 4 
 5 import com.example.android_data_storage_sdcard.file.FileUitls;
 6 
 7 public class MyTest extends AndroidTestCase {
 8     
 9     public void test() {
10         FileUitls fileUitls = new FileUitls();
11         fileUitls.saveFileToSdcard("keji.txt", "橘子洲头".getBytes());
12     }
13 }

 


  
posted @ 2015-03-29 11:31  HEWU  阅读(410)  评论(0编辑  收藏  举报