android开发SD卡工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android开发SD卡工具类相关的知识,希望对你有一定的参考价值。

SD卡工具类整理:

  1 package com.gzcivil.utils;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.io.OutputStream;
 10 import java.math.BigDecimal;
 11 
 12 import android.os.Environment;
 13 
 14 /**
 15  * SD卡工具类
 16  */
 17 public class SDTool {
 18     // 字节参考量(bt/KB/MB/GB/TB)
 19     protected final long SIZE_BT = 1024L;
 20     protected final long SIZE_KB = SIZE_BT * 1024L;
 21     protected final long SIZE_MB = SIZE_KB * 1024L;
 22     protected final long SIZE_GB = SIZE_MB * 1024L;
 23     protected final long SIZE_TB = SIZE_GB * 1024L;
 24     protected final int SACLE = 2;
 25 
 26     private static SDTool mSDTool;
 27     private final String mModuleName = this.getClass().getSimpleName();
 28     private static boolean SDCardAvailable = false; // SDCard有效状态
 29     private static String SDCardRootDir = ""; // SDCard路径
 30 
 31     private SDTool() {
 32         super();
 33         LogUtils.i(SysUtils.LOG_TAG, "创建文件夹");
 34         this.initSDTool();
 35     }
 36 
 37     public static synchronized SDTool getInstance() {
 38         if (mSDTool == null)
 39             mSDTool = new SDTool();
 40         return mSDTool;
 41     }
 42 
 43     // --------------------------get some dir path....
 44     public String getBaseDir() {
 45         return SDCardAvailable ? SDCardRootDir + SysConstants.PATH_ROOT : null;
 46     }
 47 
 48     /** 获取图片sdcard保存路径 */
 49     public String getImgDir(String urlFileName) {
 50         if (SDCardAvailable)
 51             return SDCardRootDir + SysConstants.PATH_IMAGE + urlFileName;
 52         return null;
 53     }
 54 
 55     /** 获取上传图片sdcard保存路径 */
 56     public String getUpImgDir(String urlFileName) {
 57         if (SDCardAvailable)
 58             return SDCardRootDir + SysConstants.PATH_UPIMAGE + urlFileName;
 59         return null;
 60     }
 61 
 62     /** 获取sdcard临时目录的路径 */
 63     public String getTempBase() {
 64         if (SDCardAvailable)
 65             return SDCardRootDir + SysConstants.PATH_TEMP;
 66         return null;
 67     }
 68 
 69     /** 获取sdcard下载目录的路径 */
 70     public String getDownloadBase() {
 71         if (SDCardAvailable)
 72             return SDCardRootDir + SysConstants.PATH_DOWNLOAD;
 73         return null;
 74     }
 75 
 76     /** 获取sdcard数据库目录的路径 */
 77     public String getDataBase() {
 78         if (SDCardAvailable)
 79             return SDCardRootDir + SysConstants.PATH_DATABASE;
 80         return null;
 81     }
 82 
 83     /** 获取文件在sdcard临时目录的保存路径 */
 84     public String getTempDir(String urlFileName) {
 85         if (SDCardAvailable)
 86             return SDCardRootDir + SysConstants.PATH_TEMP + urlFileName;
 87         return null;
 88     }
 89 
 90     /** 获取文件在sdcard临时目录的保存路径 */
 91     public String getTempDirUpImage(String urlFileName) {
 92         if (SDCardAvailable)
 93             return SDCardRootDir + SysConstants.PATH_UPIMAGE;
 94         return null;
 95     }
 96 
 97     /**
 98      * 根据SD卡相对路径返回绝对路径
 99      * 
100      * @param filePath
101      * @return
102      */
103     public String getSdFullPath(String filePath) {
104         return SDCardRootDir + filePath;
105     }
106 
107     // --------------------------public function....
108     /**
109      * SD卡可用状态检测
110      */
111     public static boolean isAvailable() {
112         return SDCardAvailable;
113     }
114 
115     /**
116      * 检测文件是否存在
117      */
118     public boolean exists(String filePath) {
119         return SDCardAvailable ? new File(filePath).exists() : false;
120     }
121 
122     /**
123      * 检测是否为零字节文件
124      */
125     public boolean emptyFile(String filePath) {
126         return (!SDCardAvailable || new File(filePath).length() < 1) ? true : false;
127     }
128 
129     /**
130      * 根据文件名删除文件
131      * 
132      * @param filePath
133      *            SDCard卡上完整路径
134      * @return void
135      */
136     public void deleteFile(String filePath) {
137         if (!SDCardAvailable || StringUtils.isEmpty(filePath))
138             return;
139         File file = new File(filePath);
140         if (file.exists())
141             file.delete();
142     }
143 
144     /**
145      * 删除指定目录下所有文件及子目录(不包含自身)
146      * 
147      * @param dirPath
148      * @return
149      * @return void
150      */
151     public synchronized boolean deleteDir(String dirPath) {
152         boolean clearFlag = false;
153         if (!SDCardAvailable) {
154             return false;
155         }
156 
157         File file = new File(dirPath);
158         if (file.exists() && file.isDirectory()) {
159             File[] files = file.listFiles();
160             for (File fileItem : files) {
161                 if (fileItem.isFile()) {
162                     fileItem.delete();
163                 }
164             }
165             clearFlag = true;
166         }
167         return clearFlag;
168     }
169 
170     /**
171      * 获取指定目录大小
172      * 
173      * @param dirPath
174      * @return
175      */
176     public long getPathSize(String dirPath) {
177         long size = 0;
178         if (!SDCardAvailable)
179             return size;
180 
181         File file = new File(dirPath);
182         if (file.exists() && file.isDirectory()) {
183             File[] files = file.listFiles();
184             for (File fileItem : files) {
185                 if (fileItem.isFile()) {
186                     size += fileItem.length();
187                 }
188             }
189         }
190         return size;
191     }
192 
193     /**
194      * 读取SD卡中文本文件
195      * 
196      * @param fileName
197      * @return
198      */
199 
200     public String readSDFile(String fileName) {
201         StringBuffer sb = new StringBuffer();
202         try {
203             File file = new File(fileName);
204             FileInputStream fis = new FileInputStream(file);
205             int c;
206             while ((c = fis.read()) != -1) {
207                 sb.append((char) c);
208             }
209             fis.close();
210         } catch (FileNotFoundException e) {
211             e.printStackTrace();
212         } catch (IOException e) {
213             e.printStackTrace();
214         } catch (Exception e) {
215             e.printStackTrace();
216         }
217         return sb.toString();
218     }
219 
220     /**
221      * 获取指定目录大小-格式化好字串
222      * 
223      * @param dirPath
224      * @return
225      */
226     public String sizeFormatString(long size) {
227         String sizeFormat = "";
228         if (size >= 0 && size < SIZE_BT) {
229             sizeFormat = size + " Byte";
230         } else if (size >= SIZE_BT && size < SIZE_KB) {
231             sizeFormat = size / SIZE_BT + " KB";
232         } else if (size >= SIZE_KB && size < SIZE_MB) {
233             sizeFormat = size / SIZE_KB + " MB";
234         } else if (size >= SIZE_MB && size < SIZE_GB) {
235             BigDecimal longs = new BigDecimal(Double.valueOf(size + "").toString());
236             BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "").toString());
237             String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString();
238             // double result=size/(double)SIZE_MB;
239             sizeFormat = result + " GB";
240         } else {
241             BigDecimal longs = new BigDecimal(Double.valueOf(size + "").toString());
242             BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "").toString());
243             String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString();
244             sizeFormat = result + " TB";
245         }
246         return sizeFormat;
247     }
248 
249     /**
250      * 文件拷贝
251      * 
252      * @param fromFile
253      * @param toFile
254      * @return
255      */
256     public boolean CopySdcardFile(String fromFile, String toFile) {
257         boolean copyState = false;
258         try {
259             InputStream fosfrom = new FileInputStream(fromFile);
260             OutputStream fosto = new FileOutputStream(toFile);
261             byte bt[] = new byte[1024];
262             int c;
263             while ((c = fosfrom.read(bt)) > 0) {
264                 fosto.write(bt, 0, c);
265             }
266             fosfrom.close();
267             fosto.close();
268             copyState = true;
269         } catch (Exception ex) {
270             LogUtils.e(SysUtils.LOG_TAG, "CopySdcardFile Exception: fromFile=" + fromFile + " toFile=" + toFile + " 复制失败.", this.mModuleName);
271         }
272         return copyState;
273     }
274 
275     // ==============================================
276     protected String getMd5(String urlName) {
277         return StringUtils.md5(urlName.getBytes());
278     }
279 
280     @SuppressWarnings("static-access")
281     private void initSDTool() {
282         if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
283             return;
284         }
285         SDCardAvailable = true;
286         SDCardRootDir = Environment.getExternalStorageDirectory().getPath();
287 
288         this.initSDDir(SDCardRootDir + SysConstants.PATH_ROOT);
289         this.initSDDir(SDCardRootDir + SysConstants.PATH_IMAGE);
290         this.initSDDir(SDCardRootDir + SysConstants.PATH_DATABASE);
291         this.initSDDir(SDCardRootDir + SysConstants.PATH_DOWNLOAD);
292         this.initSDDir(SDCardRootDir + SysConstants.PATH_TEMP);
293         this.initSDDir(SDCardRootDir + SysConstants.PATH_UPIMAGE);
294     }
295 
296     /**
297      * 获取SDCard根路径
298      */
299     public static String getSDCardRootDir() {
300         return SDCardRootDir;
301     }
302 
303     public static boolean initSDDir(String dirPath) {
304         boolean flag = false;
305         if (SDCardAvailable) {
306             File tempFile = new File(dirPath);
307             if (!tempFile.exists()) {
308                 if (tempFile.mkdirs()) {
309                     flag = true;
310                     LogUtils.v(SysUtils.LOG_TAG, "tempFile=" + dirPath + " mkdir success!");
311                 }
312             } else {
313                 flag = true;
314                 LogUtils.v(SysUtils.LOG_TAG, "tempFile=" + dirPath + " is exist!");
315             }
316         }
317         return flag;
318     }
319 
320 }

 

以上是关于android开发SD卡工具类的主要内容,如果未能解决你的问题,请参考以下文章

Android推断是否有sd卡

Android系统下监听SD卡的插入并读取内容的代码

手动将文件放入 Android 模拟器 SD 卡

Android开发之sd卡存储和机身存储的路径获取

java SD卡相关的工具类包括获取SD卡是否可用,剩余空间,总空间,剩余空间是否足够..当然你必须先申请访问SD卡的权限。

Android4.4中不能发送SD卡就绪广播