当前位置:   article > 正文

Android学习笔记之数据的Sdcard存储方法及操作sdcard的工具类_sdcard类的方法

sdcard类的方法


(1)文件的目录


(2)各文件的代码:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:paddingBottom="@dimen/activity_vertical_margin"
  6. android:paddingLeft="@dimen/activity_horizontal_margin"
  7. android:paddingRight="@dimen/activity_horizontal_margin"
  8. android:paddingTop="@dimen/activity_vertical_margin"
  9. tools:context=".MainActivity" >
  10. <ImageView
  11. android:id="@+id/imageView1"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:layout_alignParentTop="true"
  15. android:layout_alignRight="@+id/button1"
  16. android:layout_marginRight="44dp"
  17. android:layout_marginTop="78dp"
  18. android:src="@drawable/ic_launcher" />
  19. <Button
  20. android:id="@+id/button1"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:layout_alignParentLeft="true"
  24. android:layout_below="@+id/imageView1"
  25. android:layout_marginLeft="96dp"
  26. android:layout_marginTop="106dp"
  27. android:text="Button" />
  28. </RelativeLayout>


FileService.java也就是操作sdcard的工具类:

  1. package com.example.data_storage_sdcard.file;
  2. import java.io.ByteArrayOutputStream;
  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 android.os.Environment;
  9. /**
  10. * sdcard的存在于上下文无关
  11. *
  12. * @author piaodangdehun
  13. *
  14. */
  15. public class FileService {
  16. /*
  17. * 存放在sdcard的根目录
  18. */
  19. public boolean saveFileToSdcardRoot(String fileName, byte[] data) {
  20. boolean flag = false;
  21. /*
  22. * 先判断sdcard的状态,是否存在
  23. */
  24. String state = Environment.getExternalStorageState();
  25. FileOutputStream outputStream = null;
  26. File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径
  27. /*
  28. * 表示sdcard挂载在手机上,并且可以读写
  29. */
  30. if (state.equals(Environment.MEDIA_MOUNTED)) {
  31. File file = new File(rootFile, fileName);
  32. try {
  33. outputStream = new FileOutputStream(file);
  34. try {
  35. outputStream.write(data, 0, data.length);
  36. flag = true;
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. } catch (FileNotFoundException e) {
  41. e.printStackTrace();
  42. } finally {
  43. if (outputStream != null) {
  44. try {
  45. outputStream.close();
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. }
  52. return flag;
  53. }
  54. /*
  55. * 存放在sdcard下自定义的目录
  56. */
  57. public boolean saveFileToSdcardDir(String fileName, byte[] data) {
  58. boolean flag = false;
  59. /*
  60. * 先判断sdcard的状态,是否存在
  61. */
  62. String state = Environment.getExternalStorageState();
  63. FileOutputStream outputStream = null;
  64. File rootFile = Environment.getExternalStorageDirectory(); // 获得sdcard的根路径
  65. /*
  66. * 表示sdcard挂载在手机上,并且可以读写
  67. */
  68. if (state.equals(Environment.MEDIA_MOUNTED)) {
  69. File file = new File(rootFile.getAbsoluteFile() + "/txt");
  70. if (!file.exists()) {
  71. file.mkdirs();
  72. }
  73. try {
  74. outputStream = new FileOutputStream(new File(file, fileName));
  75. try {
  76. outputStream.write(data, 0, data.length);
  77. flag = true;
  78. } catch (IOException e) {
  79. e.printStackTrace();
  80. }
  81. } catch (FileNotFoundException e) {
  82. e.printStackTrace();
  83. } finally {
  84. if (outputStream != null) {
  85. try {
  86. outputStream.close();
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91. }
  92. }
  93. return flag;
  94. }
  95. /*
  96. * 用于读取sdcard的数据
  97. */
  98. public String readContextFromSdcard(String fileName) {
  99. String state = Environment.getExternalStorageState();
  100. File rooFile = Environment.getExternalStorageDirectory(); // 获得sdcard的目录
  101. FileInputStream inputStream = null;// 用于度取数据的流
  102. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 用于存放独处的数据
  103. if (state.equals(Environment.MEDIA_MOUNTED)) {
  104. File file = new File(rooFile.getAbsoluteFile() + "/txt/");// 在sdcard目录下创建一个txt目录
  105. File file2 = new File(file, fileName);
  106. int len = 0;
  107. byte[] data = new byte[1024];
  108. if (file2.exists()) {
  109. try {
  110. inputStream = new FileInputStream(file2);
  111. try {
  112. while ((len = inputStream.read(data)) != -1) {
  113. outputStream.write(data, 0, data.length);
  114. }
  115. } catch (IOException e) {
  116. e.printStackTrace();
  117. }
  118. return new String(outputStream.toByteArray());
  119. } catch (FileNotFoundException e) {
  120. // TODO Auto-generated catch block
  121. e.printStackTrace();
  122. } finally {
  123. if (outputStream != null) {
  124. try {
  125. outputStream.close();
  126. } catch (IOException e) {
  127. e.printStackTrace();
  128. }
  129. }
  130. }
  131. }
  132. }
  133. return null;
  134. }
  135. /**
  136. * 对文件进行分类的保存到固定的文件中去
  137. *
  138. * @param fileName
  139. * @param data
  140. */
  141. public void saveFileToSdcardBySuff(String fileName, byte[] data) {
  142. // File file = Environment.getExternalStoragePublicDirectory("");
  143. // 保存文件的目录
  144. File file = null;
  145. if (Environment.getExternalStorageState().equals(
  146. Environment.MEDIA_MOUNTED)) {
  147. /*
  148. * 将不同的文件放入到不同的类别中
  149. */
  150. if (fileName.endsWith(".mp3")) {
  151. file = Environment
  152. .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
  153. } else if (fileName.endsWith(".jpg") || fileName.endsWith(".png")
  154. || fileName.endsWith(".gif")) {
  155. file = Environment
  156. .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
  157. } else if (fileName.endsWith(".mp4") || fileName.endsWith(".avi")
  158. || fileName.endsWith(".3gp")) {
  159. file = Environment
  160. .getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
  161. } else {
  162. file = Environment
  163. .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
  164. }
  165. FileOutputStream outputStream = null;
  166. try {
  167. outputStream = new FileOutputStream(new File(file, fileName));
  168. try {
  169. outputStream.write(data, 0, data.length);
  170. } catch (IOException e) {
  171. e.printStackTrace();
  172. }
  173. } catch (FileNotFoundException e) {
  174. e.printStackTrace();
  175. } finally {
  176. if (outputStream != null) {
  177. try {
  178. outputStream.close();
  179. } catch (IOException e) {
  180. e.printStackTrace();
  181. }
  182. }
  183. }
  184. }
  185. }
  186. /*
  187. * 删除一个文件
  188. */
  189. public boolean deleteFileFromSdcard(String folder, String fileName) {
  190. boolean flag = false;
  191. File file = Environment.getExternalStorageDirectory();
  192. if (Environment.getExternalStorageState().equals(
  193. Environment.MEDIA_MOUNTED)) {
  194. File exitFile = new File(file.getAbsoluteFile() + "/" + folder);
  195. if (exitFile.exists()) {
  196. exitFile.delete();
  197. }
  198. }
  199. return flag;
  200. }
  201. }

HttpUtils.java访问网络的

  1. package com.example.data_storage_sdcard.http;
  2. import java.io.IOException;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.ClientProtocolException;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.impl.client.DefaultHttpClient;
  8. import org.apache.http.util.EntityUtils;
  9. public class HttpUtils {
  10. /*
  11. *
  12. */
  13. public static byte[] getImage(String path) {
  14. byte[] data = null;
  15. HttpClient httpClient = new DefaultHttpClient();
  16. HttpPost httpPost = new HttpPost(path);
  17. try {
  18. HttpResponse response = httpClient.execute(httpPost);
  19. if (response.getStatusLine().getStatusCode() == 200) {
  20. data = EntityUtils.toByteArray(response.getEntity());
  21. }
  22. } catch (ClientProtocolException e) {
  23. e.printStackTrace();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. } finally {
  27. httpClient.getConnectionManager().shutdown();
  28. }
  29. return data;
  30. }
  31. }

ImageCache.java将文件放到cache中的:

  1. package com.example.data_storage_sdcard.img;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import android.os.Environment;
  6. public class ImageCache {
  7. public static String saveImageCache(String fileName, byte[] data) {
  8. File file = Environment.getExternalStorageDirectory(); // 根目录
  9. FileOutputStream outputStream = null;
  10. if (Environment.getExternalStorageState().equals(
  11. Environment.MEDIA_MOUNTED)) {
  12. try {
  13. outputStream = new FileOutputStream(new File(file, fileName));
  14. outputStream.write(data, 0, data.length);
  15. return file.getAbsolutePath() + "/" + fileName;
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. } finally {
  19. if (outputStream != null) {
  20. try {
  21. outputStream.close();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. }
  28. return null;
  29. }
  30. }

MainActivity.java

  1. package com.example.data_storage_sdcard;
  2. import android.app.Activity;
  3. import android.app.ProgressDialog;
  4. import android.graphics.Bitmap;
  5. import android.graphics.BitmapFactory;
  6. import android.os.AsyncTask;
  7. import android.os.Bundle;
  8. import android.view.Menu;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.widget.Button;
  12. import android.widget.ImageView;
  13. import com.example.data_storage_sdcard.http.HttpUtils;
  14. import com.example.data_storage_sdcard.img.ImageCache;
  15. public class MainActivity extends Activity {
  16. private Button button;
  17. private ImageView imageView;
  18. private ProgressDialog progressDialog;
  19. private String imageName;
  20. private final String pathString = "http://www.baidu.com/img/bd_logo1.png";
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25. button = (Button) this.findViewById(R.id.button1);
  26. imageView = (ImageView) this.findViewById(R.id.imageView1);
  27. progressDialog = new ProgressDialog(this);
  28. progressDialog.setTitle("下载提示");
  29. progressDialog.setMessage("load...");
  30. button.setOnClickListener(new OnClickListener() {
  31. @Override
  32. public void onClick(View v) {
  33. new MyTask().execute(pathString);
  34. }
  35. });
  36. }
  37. class MyTask extends AsyncTask<String, Void, byte[]> {
  38. @Override
  39. protected void onPreExecute() {
  40. super.onPreExecute();
  41. progressDialog.show();
  42. }
  43. @Override
  44. protected byte[] doInBackground(String... params) {
  45. String name = params[0];
  46. imageName = name
  47. .substring(name.lastIndexOf("/") + 1, name.length());
  48. return HttpUtils.getImage(params[0]);
  49. }
  50. @Override
  51. protected void onProgressUpdate(Void... values) {
  52. super.onProgressUpdate(values);
  53. }
  54. @Override
  55. protected void onPostExecute(byte[] result) {
  56. super.onPostExecute(result);
  57. if (result != null) {
  58. Bitmap bm = BitmapFactory.decodeByteArray(result, 0,
  59. result.length);
  60. imageView.setImageBitmap(bm);
  61. ImageCache.saveImageCache("", result);
  62. } else {
  63. imageView.setImageResource(R.drawable.ic_launcher);
  64. }
  65. progressDialog.dismiss();
  66. }
  67. }
  68. @Override
  69. public boolean onCreateOptionsMenu(Menu menu) {
  70. // Inflate the menu; this adds items to the action bar if it is present.
  71. getMenuInflater().inflate(R.menu.main, menu);
  72. return true;
  73. }
  74. }

测试类:

  1. package com.example.data_storage_sdcard;
  2. import java.io.FileWriter;
  3. import com.example.data_storage_sdcard.file.FileService;
  4. import android.nfc.Tag;
  5. import android.test.AndroidTestCase;
  6. import android.util.Log;
  7. public class MyTest extends AndroidTestCase {
  8. public void saveFileToSdcardTest() {
  9. FileService fileService = new FileService();
  10. fileService.saveFileToSdcardRoot("aa.txt",
  11. "jkhdsfjkhdskjfhdsjf".getBytes());
  12. }
  13. public void saveFileToSdcardDir() {
  14. FileService fileService = new FileService();
  15. fileService.saveFileToSdcardRoot("aa.txt",
  16. "jkhdsfjkhdskjfhdsjf".getBytes());
  17. }
  18. public void readContextFromSdcardTest() {
  19. FileService fileService = new FileService();
  20. String msg = fileService.readContextFromSdcard("aa.txt");
  21. System.err.println("-->" + msg);
  22. }
  23. public void saveFileToSdcardBySuffTest() {
  24. FileService fileService = new FileService();
  25. fileService.saveFileToSdcardBySuff("aa.avi",
  26. "asdfkajsgdhagsdfhdgsf".getBytes());
  27. }
  28. public void delFile() {
  29. FileService fileService = new FileService();
  30. boolean flag = fileService.deleteFileFromSdcard("txt", "aa.txt");
  31. }
  32. }

需要在请单位按中加入访问网络的权限、操作sdcard的权限、测试的权限

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.example.data_storage_sdcard"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk
  7. android:minSdkVersion="8"
  8. android:targetSdkVersion="18" />
  9. <instrumentation
  10. android:name="android.test.InstrumentationTestRunner"
  11. android:targetPackage="com.example.data_storage_sdcard" >
  12. </instrumentation>
  13. <!-- 添加访问sdcard的权限 -->
  14. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  15. <!-- 添加访问网络的权限 -->
  16. <uses-permission android:name="android.permission.INTERNET" />
  17. <application
  18. android:allowBackup="true"
  19. android:icon="@drawable/ic_launcher"
  20. android:label="@string/app_name"
  21. android:theme="@style/AppTheme" >
  22. <uses-library android:name="android.test.runner" />
  23. <activity
  24. android:name="com.example.data_storage_sdcard.MainActivity"
  25. android:label="@string/app_name" >
  26. <intent-filter>
  27. <action android:name="android.intent.action.MAIN" />
  28. <category android:name="android.intent.category.LAUNCHER" />
  29. </intent-filter>
  30. </activity>
  31. <uses-library>
  32. </uses-library>
  33. </application>
  34. </manifest>




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/319263
推荐阅读
相关标签
  

闽ICP备14008679号