1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import android.os.Environment;
  7. import android.os.StatFs;
  8. import android.util.Log;
  9. public class FileUtil {
  10. private static int bufferd = 1024;
  11. private FileUtil() {
  12. }
  13. /*
  14. * <!-- 在SDCard中创建与删除文件权限 --> <uses-permission
  15. * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--
  16. * 往SDCard写入数据权限 --> <uses-permission
  17. * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  18. */
  19. // =================get SDCard information===================
  20. public static boolean isSdcardAvailable() {
  21. String status = Environment.getExternalStorageState();
  22. if (status.equals(Environment.MEDIA_MOUNTED)) {
  23. return true;
  24. }
  25. return false;
  26. }
  27. public static long getSDAllSizeKB() {
  28. // get path of sdcard
  29. File path = Environment.getExternalStorageDirectory();
  30. StatFs sf = new StatFs(path.getPath());
  31. // get single block size(Byte)
  32. long blockSize = sf.getBlockSize();
  33. // 获取所有数据块数
  34. long allBlocks = sf.getBlockCount();
  35. // 返回SD卡大小
  36. return (allBlocks * blockSize) / 1024; // KB
  37. }
  38. /**
  39. * free size for normal application
  40. *
  41. * @return
  42. */
  43. public static long getSDAvalibleSizeKB() {
  44. File path = Environment.getExternalStorageDirectory();
  45. StatFs sf = new StatFs(path.getPath());
  46. long blockSize = sf.getBlockSize();
  47. long avaliableSize = sf.getAvailableBlocks();
  48. return (avaliableSize * blockSize) / 1024;// KB
  49. }
  50. // =====================File Operation==========================
  51. public static boolean isFileExist(String director) {
  52. File file = new File(Environment.getExternalStorageDirectory()
  53. + File.separator + director);
  54. return file.exists();
  55. }
  56. /**
  57. * create multiple director
  58. *
  59. * @param path
  60. * @return
  61. */
  62. public static boolean createFile(String director) {
  63. if (isFileExist(director)) {
  64. return true;
  65. } else {
  66. File file = new File(Environment.getExternalStorageDirectory()
  67. + File.separator + director);
  68. if (!file.mkdirs()) {
  69. return false;
  70. }
  71. return true;
  72. }
  73. }
  74. public static File writeToSDCardFile(String directory, String fileName,
  75. String content, boolean isAppend) {
  76. return writeToSDCardFile(directory, fileName, content, "", isAppend);
  77. }
  78. /**
  79. *
  80. * @param director
  81. *            (you don't need to begin with
  82. *            Environment.getExternalStorageDirectory()+File.separator)
  83. * @param fileName
  84. * @param content
  85. * @param encoding
  86. *            (UTF-8...)
  87. * @param isAppend
  88. *            : Context.MODE_APPEND
  89. * @return
  90. */
  91. public static File writeToSDCardFile(String directory, String fileName,
  92. String content, String encoding, boolean isAppend) {
  93. // mobile SD card path +path
  94. File file = null;
  95. OutputStream os = null;
  96. try {
  97. if (!createFile(directory)) {
  98. return file;
  99. }
  100. file = new File(Environment.getExternalStorageDirectory()
  101. + File.separator + directory + File.separator + fileName);
  102. os = new FileOutputStream(file, isAppend);
  103. if (encoding.equals("")) {
  104. os.write(content.getBytes());
  105. } else {
  106. os.write(content.getBytes(encoding));
  107. }
  108. os.flush();
  109. } catch (IOException e) {
  110. Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage());
  111. } finally {
  112. try {
  113. if(os != null){
  114. os.close();
  115. }
  116. } catch (IOException e) {
  117. e.printStackTrace();
  118. }
  119. }
  120. return file;
  121. }
  122. /**
  123. * write data from inputstream to SDCard
  124. */
  125. public File writeToSDCardFromInput(String directory, String fileName,
  126. InputStream input) {
  127. File file = null;
  128. OutputStream os = null;
  129. try {
  130. if (createFile(directory)) {
  131. return file;
  132. }
  133. file = new File(Environment.getExternalStorageDirectory()
  134. + File.separator + directory + fileName);
  135. os = new FileOutputStream(file);
  136. byte[] data = new byte[bufferd];
  137. int length = -1;
  138. while ((length = input.read(data)) != -1) {
  139. os.write(data, 0, length);
  140. }
  141. // clear cache
  142. os.flush();
  143. } catch (Exception e) {
  144. Log.e("FileUtil", "" + e.getMessage());
  145. e.printStackTrace();
  146. } finally {
  147. try {
  148. os.close();
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. return file;
  154. }
  155. /**
  156. * this url point to image(jpg)
  157. *
  158. * @param url
  159. * @return image name
  160. */
  161. public static String getUrlLastString(String url) {
  162. String[] str = url.split("/");
  163. int size = str.length;
  164. return str[size - 1];
  165. }
  166. }

下面对代码进行了测试,使用了AndroidJunitTest,当然另外还需要对SDCard查看操作的权限。

1、对android项目的mainfest.xml进行配置,需要注意targetPacket应当与包名保持一致。

  1. //在mainfest标签下
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  3. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
  4. <instrumentation
  5. android:name="android.test.InstrumentationTestRunner"
  6. android:targetPackage="com.example.mygeneralutil" >
  7. </instrumentation>
  8. //在mainfest的application标签下
  9. <uses-library android:name="android.test.runner"/>

2、简单的测试代码如下:

  1. import android.test.AndroidTestCase;
  2. import android.util.Log;
  3. public class FileUtilTest extends AndroidTestCase {
  4. public void testIsSdcardAvailable() {
  5. FileUtil.isSdcardAvailable();
  6. Log.e("FileUtil", ""+FileUtil.isSdcardAvailable());
  7. }
  8. public void testGetSDAllSizeKB() {
  9. FileUtil.getSDAllSizeKB();
  10. Log.e("FileUtil", ""+(float)FileUtil.getSDAllSizeKB()/1024/1024);
  11. }
  12. public void testGetSDAvalibleSizeKB() {
  13. FileUtil.getSDAvalibleSizeKB();
  14. Log.e("FileUtil", ""+(float)FileUtil.getSDAvalibleSizeKB()/1024/1024);
  15. }
  16. public void testIsFileExist() {
  17. FileUtil.isFileExist("example");
  18. Log.e("FileUtil", ""+FileUtil.isFileExist("example"));
  19. }
  20. public void testCreateFile() {
  21. Log.e("FileUtil", ""+FileUtil.createFile("forexample"));
  22. }
  23. public void testWriteToSDCardFileStringStringStringBoolean() {
  24. fail("Not yet implemented");
  25. }
  26. public void testWriteToSDCardFileStringStringStringStringBoolean() {
  27. FileUtil.writeToSDCardFile("forexample", "123.txt",
  28. "FileUtil.writeToSDCardFile", "utf-8", true);
  29. }
  30. public void testWriteToSDCardFromInput() {
  31. fail("Not yet implemented");
  32. }
  33. public void testGetUrlLastString() {
  34. fail("Not yet implemented");
  35. }
  36. }

最新文章

  1. hibernate与Struts框架结合编写简单针对修改练习
  2. Devexpress GridView 列中显示图片
  3. 在浏览器的背后(二) —— HTML语言的语法解析
  4. Switch语句的case穿透
  5. python脚本生成exe可执行文件
  6. C# 属性和索引
  7. 对话框Dialog
  8. ES6入门之函数的扩展
  9. shell脚本操作mysql库
  10. 【工作记录】android手势事件操作记录
  11. Android重力感应开发
  12. Flash AIR 保存与读取
  13. Socket 基础解析使用ServerSocket建立聊天服务器
  14. 基于visual Studio2013解决C语言竞赛题之0510求最大和
  15. Jenkins配置从节点
  16. 关于easy ui 的combobox遍历选中
  17. opencv学习之路(28)、轮廓查找与绘制(七)——位置关系及轮廓匹配
  18. 学会4种备份MySQL数据库(基本备份方面没问题了)
  19. 《Android进阶之光》--Material Design
  20. PHP 数据运算类型都有哪些?

热门文章

  1. php curl函数实例
  2. OpenCV学习 3:平滑过度与边缘检测
  3. SQL Server 判断数据库是否存在,表是否存在
  4. oracle 高级分组
  5. 让两个Div并排显示
  6. 权威验证:MSDN会明确告诉你下载的光盘镜像是否正宗微软原版
  7. C++中顶层const和底层const
  8. 一个解析url参数方法
  9. 关于消息推送和service的一些调查-清理内存通知栏点击无响应
  10. ##DAY10 UITableView基础