Android入门开发之SD卡读写操作(转)

 SD卡的读写是我们在开发android 应用程序过程中最常见的操作。下面介绍SD卡的读写操作方式:

   

   1. 获取SD卡的根目录

 

  1. String  sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();   



 

 

   2. 在SD卡上创建文件夹目录

 

  1. /** 
  2.  * 在SD卡上创建目录 
  3.  */  
  4. public File createDirOnSDCard(String dir)  
  5. {  
  6.     File dirFile = new File(sdCardRoot + File.separator + dir +File.separator);  
  7.     Log.v("createDirOnSDCard", sdCardRoot + File.separator + dir +File.separator);  
  8.     dirFile.mkdirs();  
  9.     return dirFile;  
  10. }  

 

 


    3. 在SD卡上创建文件

 

  1. /** 
  2.  * 在SD卡上创建文件 
  3.  */  
  4. public File createFileOnSDCard(String fileName, String dir) throws IOException  
  5. {  
  6.     File file = new File(sdCardRoot + File.separator + dir + File.separator + fileName);  
  7.     Log.v("createFileOnSDCard", sdCardRoot + File.separator + dir + File.separator + fileName);  
  8.     file.createNewFile();  
  9.     return file;  
  10. }  

 

 


      4.判断文件是否存在于SD卡的某个目录

  

  1. /** 
  2.  * 判断SD卡上文件是否存在 
  3.  */  
  4. public boolean isFileExist(String fileName, String path)  
  5. {  
  6.     File file = new File(sdCardRoot + path + File.separator + fileName);  
  7.     return file.exists();  
  8. }  

 

 

 

       5.将数据写入到SD卡指定目录文件

 

  1. <span style="white-space:pre">  </span>/** 
  2.      * 写入数据到SD卡中 
  3.      */  
  4.     public File writeData2SDCard(String path, String fileName, InputStream data)  
  5.     {  
  6.         File file = null;  
  7.         OutputStream output = null;  
  8.           
  9.         try {  
  10.             createDirOnSDCard(path);  //创建目录  
  11.             file = createFileOnSDCard(fileName, path);  //创建文件  
  12.             output = new FileOutputStream(file);  
  13.             byte buffer[] = new byte[2*1024];          //每次写2K数据  
  14.             int temp;  
  15.             while((temp = data.read(buffer)) != -1 )  
  16.             {  
  17.                 output.write(buffer,0,temp);  
  18.             }  
  19.             output.flush();  
  20.               
  21.         } catch (Exception e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.         finally{  
  25.             try {  
  26.                 output.close();    //关闭数据流操作  
  27.             } catch (Exception e2) {  
  28.                 e2.printStackTrace();  
  29.             }  
  30.         }  
  31.           
  32.         return file;  
  33.     }  

 

    one more important thing:

      对SD卡的操作,必须要申请权限:    

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

转自:http://blog.csdn.net/newjerryj/article/details/8829179

posted @ 2015-01-09 11:20  杨斌_济南  阅读(600)  评论(0编辑  收藏  举报