代码改变世界

android SD卡的读写

2010-11-03 13:55  stulife  阅读(10371)  评论(2编辑  收藏  举报

在AndroidManifest.xml中加入:

  1. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
  2. </uses-permission>
其次:确保SD卡的镜像文件不是Read-Only属性的,不能写入内容

 

写入SD卡:

  1. File f = new File(android.os.Environment.getExternalStorageDirectory()+"/aaa.txt");
  2. String str="this is a test about Write SD card file";
  3. 方法A:
  4. FileOutputStream fileOS=new FileOutputStream(f);
  5. fileOS.write(str.getBytes());
  6. fileOS.close();
  7. BufferedWriter buf = new BufferedWriter (new OutputStreamWriter(fileOS));
  8. buf.write(str,0,str.length());
  9. buf.flush();
  10. buf.close();
方法B:
  1. //         FileWriter fw = new FileWriter("/sdcard/cc.txt");
  2. //            fw.write(str);
  3. //            fw.close();

读SD卡
  1. File file[] = android.os.Environment.getExternalStorageDirectory().listFiles();  
  2.          //这里我们只是取得列表中的第二个文件的绝对路径
  3.          String path=file[1].getAbsolutePath();
  4. try{
  5.          
  6.             FileInputStream fileIS = new FileInputStream(path);
  7.            BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
  8.             String readString = new String();
  9.             //just reading each line and pass it on the debugger
  10.            while((readString = buf.readLine())!= null){
  11.                 Log.d("line: ", readString);
  12.              }
  13.             fileIS.close();
  14.           } catch (FileNotFoundException e) {
  15.              e.printStackTrace();
  16.            } catch (IOException e){
  17.             e.printStackTrace();
  18.           }
删除SD卡中的文件
  1. File file1= new File(path);
  2. boolean isdelte=file1.delete();