android 开发-数据存储之文件存储
android的文件存储是通过android的文件系统对数据进行临时的保存操作,并不是持久化数据,例如网络上下载某些图片、音频、视频文件等。如缓存文件将会在清理应用缓存的时候被清除,或者是应用卸载的时候缓存文件或内部文件将会被清除。
以下是开发学习中所写的示例代码,以供日后查阅:
xml:
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 11 <EditText 12 android:id="@+id/editText1" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:layout_alignParentLeft="true" 16 android:layout_alignParentTop="true" 17 android:layout_marginTop="44dp" 18 android:ems="10" /> 19 20 <Button 21 android:id="@+id/button1" 22 android:layout_width="wrap_content" 23 android:layout_height="wrap_content" 24 android:layout_alignRight="@+id/editText1" 25 android:layout_below="@+id/editText1" 26 android:layout_marginRight="57dp" 27 android:layout_marginTop="23dp" 28 android:text="保存信息" /> 29 30 </RelativeLayout>
activity:
1 package com.example.android_data_storage_internal; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.InputStream; 5 import java.net.URI; 6 7 import org.apache.http.HttpResponse; 8 import org.apache.http.client.HttpClient; 9 import org.apache.http.client.methods.HttpGet; 10 import org.apache.http.impl.client.DefaultHttpClient; 11 12 import android.app.Activity; 13 import android.content.Context; 14 import android.os.AsyncTask; 15 import android.os.Bundle; 16 import android.view.Menu; 17 import android.view.View; 18 import android.widget.Button; 19 import android.widget.EditText; 20 import android.widget.Toast; 21 22 import com.example.android_data_storage_internal.file.FileService; 23 /** 24 * @author xiaowu 25 * @note 数据存储之文件内容存储 26 */ 27 /** 28 * @author xiaowu 29 * @note 数据存储之文件内容存储(内部文件存储包括默认的文件存储、缓存文件存储) 30 * 通过context对象获取文件路径 31 * context.getCacheDir(); 32 * context.getFilesDir(); 33 * //操作文件的模式:如果需要多种操作模式,可对文件模式进行相加 34 //int MODE_PRIVATE 私有模式 35 //int MODE_APPEND 追加模式 36 //int MODE_WORLD_READABLE 可读 37 //int MODE_WORLD_WRITEABLE 可写 38 */ 39 public class MainActivity extends Activity { 40 private EditText editText ; 41 private Button button ; 42 private FileService fileService; 43 private final String IMAGEPATH ="http://b.hiphotos.baidu.com/zhidao/pic/item/738b4710b912c8fcda0b7362fc039245d78821a0.jpg"; 44 @Override 45 protected void onCreate(Bundle savedInstanceState) { 46 super.onCreate(savedInstanceState); 47 setContentView(R.layout.activity_main); 48 fileService = new FileService(this); 49 button = (Button) findViewById(R.id.button1); 50 editText = (EditText) findViewById(R.id.editText1); 51 //增加按钮点击监听事件 52 button.setOnClickListener(new View.OnClickListener() { 53 @Override 54 public void onClick(View v) { 55 String info = editText.getText().toString().trim(); 56 boolean flag = fileService.SaveContentToFile("info.txt", Context.MODE_APPEND, info.getBytes()); 57 if(flag){ 58 Toast.makeText(MainActivity.this, "保存文件成功", 0).show(); 59 } 60 //网络下载图片存储之本地 61 // MyTask task = new MyTask(); 62 // task.execute(IMAGEPATH); 63 } 64 }); 65 } 66 @Override 67 public boolean onCreateOptionsMenu(Menu menu) { 68 // Inflate the menu; this adds items to the action bar if it is present. 69 getMenuInflater().inflate(R.menu.main, menu); 70 return true; 71 } 72 //自定义异步任务,用于图片下载 73 public class MyTask extends AsyncTask<String, Integer, byte[]>{ 74 @Override 75 protected byte[] doInBackground(String... params) { 76 HttpClient httpClient = new DefaultHttpClient(); 77 HttpGet httpGet = new HttpGet(params[0]); 78 InputStream inputStream = null ; 79 byte[] result = null; 80 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 81 try { 82 //执行连接从response中读取数据 83 HttpResponse response = httpClient.execute(httpGet); 84 int leng = 0 ; 85 byte [] data = new byte[1024] ; 86 if (response.getStatusLine().getStatusCode() == 200) { 87 inputStream = response.getEntity().getContent(); 88 while((leng = inputStream.read(data)) != 0) { 89 byteArrayOutputStream.write(data, 0, leng); 90 } 91 } 92 result = byteArrayOutputStream.toByteArray(); 93 fileService.SaveContentToFile("info.txt", Context.MODE_APPEND, result); 94 } catch (Exception e) { 95 e.printStackTrace(); 96 }finally{ 97 //关连接 98 httpClient.getConnectionManager().shutdown(); 99 } 100 return result; 101 } 102 } 103 }
文件读写工具类Utils
1 package com.example.android_data_storage_internal.file; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 9 import android.content.Context; 10 11 /** 12 * @author xiaowu 13 * @NOTE android文件读写帮助类 14 */ 15 public class FileService { 16 private Context context; 17 18 public FileService(Context context) { 19 this.context = context; 20 } 21 22 // fileName:文件名 mode:文件操作权限 23 /** 24 * @param fileName 25 * 文件名 26 * @param mode 27 * 文件操作权限 28 * @param data 29 * 输出流读取的字节数组 30 * @return 31 */ 32 public boolean SaveContentToFile(String fileName, int mode, byte[] data) { 33 boolean flag = false; 34 FileOutputStream fileOutputStream = null; 35 try { 36 //通过文件名以及操作模式获取文件输出流 37 fileOutputStream = context.openFileOutput(fileName, mode); 38 fileOutputStream.write(data, 0, data.length); 39 } catch (Exception e) { 40 e.printStackTrace(); 41 } finally { 42 if (fileOutputStream != null) { 43 try { 44 fileOutputStream.close(); 45 } catch (Exception e) { 46 e.printStackTrace(); 47 } 48 } 49 } 50 return flag; 51 } 52 53 /** 54 * @param fileName 55 * 文件名称 56 * @return 文件内容 57 */ 58 public String readContentFromFile(String fileName) { 59 byte[] result = null; 60 FileInputStream fileInputStream = null; 61 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 62 try { 63 fileInputStream = context.openFileInput(fileName); 64 int len = 0; 65 byte[] data = new byte[1024]; 66 while ((len = fileInputStream.read(data)) != -1) { 67 outputStream.write(data, 0, len); 68 } 69 result = outputStream.toByteArray(); 70 } catch (Exception e) { 71 e.printStackTrace(); 72 } finally { 73 try { 74 outputStream.close(); 75 } catch (IOException e) { 76 // TODO Auto-generated catch block 77 e.printStackTrace(); 78 } 79 } 80 return new String(result); 81 } 82 /** 83 * @param fileName 文件名称 84 * @param mode 文件权限 85 * @param data 输出流读取的字节数组 86 * @return 是否成功标识 87 */ 88 public boolean saveCacheFile(String fileName, byte[] data) { 89 boolean flag = false; 90 //通过context对象获取文件目录 91 File file = context.getCacheDir(); 92 FileOutputStream fileOutputStream = null; 93 try { 94 File foder = new File(file.getAbsolutePath()+"/txt"); 95 if( !foder.exists() ){ 96 foder.mkdir(); //创建目录 97 } 98 fileOutputStream = new FileOutputStream(foder.getAbsolutePath()+"/"+fileName); 99 fileOutputStream.write(data, 0, data.length); 100 // context.openFileOutput("info.txt", 101 // Context.MODE_PRIVATE); 102 } catch (Exception e) { 103 e.printStackTrace(); 104 } finally { 105 try { 106 if (fileOutputStream != null) { 107 fileOutputStream.close(); 108 } 109 } catch (IOException e) { 110 // TODO Auto-generated catch block 111 e.printStackTrace(); 112 } 113 } 114 System.out.println(file.getAbsolutePath()); 115 return flag; 116 } 117 /** 118 * 获取android内存文件夹下的文件列表 119 * @param path 120 * @return 121 */ 122 public File[] listFileDir(String path){ 123 //获取目录 124 File file = context.getFilesDir(); 125 // System.out.println("-->CacheDir"+context.getCacheDir()); 126 // /data/data/com.example.android_data_storage_internal/cache 127 // System.out.println("-->FilesDir"+file); 128 // /data/data/com.example.android_data_storage_internal/files 129 File root = new File(file.getAbsolutePath()+"/"+path); 130 File[] listFiles = root.listFiles(); 131 return listFiles; 132 } 133 }
Junit单元测试类:
1 package com.example.android_data_storage_internal; 2 3 import android.content.Context; 4 import android.test.AndroidTestCase; 5 import android.util.Log; 6 7 import com.example.android_data_storage_internal.file.FileService; 8 /** 9 * @author xiaowu 10 * @note 单元测试类 11 * 12 */ 13 public class MyTest extends AndroidTestCase { 14 private final String TAG = "MyTest"; 15 16 public void save() { 17 FileService fileService = new FileService(getContext()); 18 //操作文件的模式:如果需要多种操作模式,可对文件模式进行相加 19 //int MODE_PRIVATE 私有模式 20 //int MODE_APPEND 追加模式 21 //int MODE_WORLD_READABLE 可读 22 //int MODE_WORLD_WRITEABLE 可写 23 boolean flag = fileService.SaveContentToFile("login.txt", Context.MODE_PRIVATE, 24 "你好".getBytes()); 25 Log.i(TAG, "-->"+flag); 26 } 27 public void read(){ 28 FileService fileService = new FileService(getContext()); 29 String msg = fileService.readContentFromFile("info.txt"); 30 Log.i(TAG, "--->"+msg); 31 } 32 public void test(){ 33 FileService fileService = new FileService(getContext()); 34 fileService.saveCacheFile("my.txt","小五".getBytes()); 35 } 36 public void test2(){ 37 FileService fileService = new FileService(getContext()); 38 fileService.listFileDir("my.txt"); 39 } 40 }
清单文件:
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.android_data_storage_internal" 4 android:versionCode="1" 5 android:versionName="1.0" > 6 7 <uses-sdk 8 android:minSdkVersion="8" 9 android:targetSdkVersion="18" /> 10 11 <instrumentation 12 android:name="android.test.InstrumentationTestRunner" 13 android:targetPackage="com.example.android_data_storage_internal" > 14 </instrumentation> 15 <!-- 增加用户访问网络权限 --> 16 <uses-permission android:name="android.permission.INTERNET"/> 17 18 <application 19 android:allowBackup="true" 20 android:icon="@drawable/ic_launcher" 21 android:label="@string/app_name" 22 android:theme="@style/AppTheme" > 23 <!-- 引入用与Junit测试包 --> 24 <uses-library android:name="android.test.runner" android:required="true"/> 25 <activity 26 android:name="com.example.android_data_storage_internal.MainActivity" 27 android:label="@string/app_name" > 28 <intent-filter> 29 <action android:name="android.intent.action.MAIN" /> 30 31 <category android:name="android.intent.category.LAUNCHER" /> 32 </intent-filter> 33 </activity> 34 </application> 35 36 </manifest>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。