android sd卡读写的一些笔记

在做android开发时假如需要保存一些信息,sd卡读写是必需要掌握的,图片什么的最好放在sd下,这样在界面上加载的时候更快,但是也要注意OOM的出现,对于控制OOM的出现我在上一篇讲过,这里就不在陈述了....

首先第一步:先判断SD卡是否存在

1      //判断SD卡是否存在
2      if(Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
3          System.out.println("存在");
4      } else{
5          System.out.println("不存在");
6      }

第二步:创建文件夹

 1 /**
 2      * 在SD卡上创建文件夹
 3      * @param filename
 4      * @return
 5      * @throws IOException
 6      */
 7     public File createSDFile(String filename) throws IOException{
 8         File file=new File(SDpath+filename);
 9         file.createNewFile();
10         return file;
11     }
12 
13     /**
14      * 在SD卡上创建目录
15      * @param dirname
16      * @return
17      */
18     public File createSDDir(String dirname){
19         File dir=new File(SDpath+dirname);
20         dir.mkdir();
21         return dir;
22     }
23     
24     
25 
26     /**
27      * 判断sd卡上的文件夹是否存在
28      * @param filename
29      * @return
30      */
31     public boolean  isFileExist(String filename){
32         File file=new File(SDpath+filename);
33         return file.exists();
34     }

第三步:将文件以流的形式写入sd卡中

 1 /**
 2      * 将一个Inputstream的数据写入到SD卡中去
 3      * @param path
 4      * @param filename
 5      * @param input
 6      * @return
 7      */
 8     public File writeSDfromInput(String path,String filename,InputStream input){
 9         File file=null;
10         OutputStream outputstream=null;
11         try {
12             createSDDir(path);
13             file=createSDFile(path+filename);
14             outputstream=new FileOutputStream(file);
15             byte buffer[]=new byte[4*1024];
16             while((input.read(buffer))!=-1){
17                 outputstream.write(buffer);
18             }
19             outputstream.flush();
20             
21         } catch (Exception e) {
22            e.printStackTrace();
23         }finally{
24             try {
25                 outputstream.close();
26             } catch (Exception e2) {
27                e2.printStackTrace();
28             }
29         }
30         return file;
31     }


有时候需要对某一个文件夹获取文件进行删除操作是,如下(只需要传入一个路径即可)

 1     //删除文件下的所有子项目
 2     public void deletefile(String path){
 3           File file = new File(path);
 4           if (!file.exists()) {//判断文件是否存在
 5                   return;
 6           }
 7           if (!file.isDirectory()) {
 8               return;
 9           }
10           String[] tempList = file.list();//获取该文件夹下所有的子文件,用一个临时数组存储
11           File temp = null;
12           for (int i = 0; i < tempList.length; i++) {
13                   if (path.endsWith(File.separator)) {
14                       temp = new File(path + tempList[i]);
15                   }else {
16                       temp = new File(path + File.separator + tempList[i]);}
17                   if (temp.isFile()) {
18                       temp.delete();//删除文件
19                   }
20                   if (temp.isDirectory()) {
21                       deletefile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
22                       delFolder(path+"/"+ tempList[i],path);//再删除空文件夹
23                   }
24           }
25     }
26 
27     //删除空文件
28     public void delFolder(String folderPath,String path) {
29         System.out.println("删除空文件夹=============="+folderPath);
30           try {
31                   deletefile(folderPath); //删除完里面所有内容
32                   String filePath = folderPath;
33                   filePath = filePath.toString();
34                   
35                   //删除子项文件夹
36                   java.io.File myFilePath = new java.io.File(filePath);
37                   myFilePath.delete(); //删除空文件夹
38                   
39                   //删除主文件夹
40                   java.io.File pathfile = new java.io.File(path);
41                   pathfile.delete(); //删除空文件夹
42           }
43           catch (Exception e) {
44                   System.out.println("删除文件夹操作出错");
45                   e.printStackTrace();
46           }
47       }


最后就是关于权限的问题了

1     <!-- SD卡读写权限 -->
2     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
3     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

这里补充一点:关于获取手机sd卡大小(这段代码是从网上看到到,所以就.....)

 1    //获取SD大小
 2    File file = Environment.getExternalStorageDirectory();//获取SD卡的目录
 3    StatFs statf = new StatFs(file.getAbsolutePath());
 4    long count = statf.getAvailableBlocks();
 5    long size = statf.getBlockSize();
 6    System.out.println("====sd卡可用空间:====="+ Formatter.formatFileSize(this, count*size));
 7          
 8    //获取手机存储设备的大小 
 9    File path = Environment.getDataDirectory();//获取手机存储设备的目录
10    StatFs stat = new StatFs(path.getPath());
11    long blockSize = stat.getBlockSize();
12    long availableBlocks = stat.getAvailableBlocks();
13    System.out.println("======手机内部空间:====="+ Formatter.formatFileSize(this, availableBlocks*blockSize));
14         


暂时就写到这里吧....

原文地址:https://www.cnblogs.com/yrhua/p/3512520.html