ANDROID对文件的操作

时间:2023-03-09 16:28:00
ANDROID对文件的操作
  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. }