android 开发-数据存储之文件存储
android的文件存储是通过android的文件系统对数据进行临时的保存操作,并不是持久化数据,例如网络上下载某些图片、音频、视频文件等。如缓存文件将会在清理应用缓存的时候被清除,或者是应用卸载的时候缓存文件或内部文件将会被清除。
以下是开发学习中所写的示例代码,以供日后查阅:
xml:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
- <EditText
- android:id="@+id/editText1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:layout_marginTop="44dp"
- android:ems="10" />
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignRight="@+id/editText1"
- android:layout_below="@+id/editText1"
- android:layout_marginRight="57dp"
- android:layout_marginTop="23dp"
- android:text="保存信息" />
- </RelativeLayout>
activity_main.xml
activity:
- package com.example.android_data_storage_internal;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.net.URI;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.impl.client.DefaultHttpClient;
- import android.app.Activity;
- import android.content.Context;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- import com.example.android_data_storage_internal.file.FileService;
- /**
- * @author xiaowu
- * @note 数据存储之文件内容存储
- */
- /**
- * @author xiaowu
- * @note 数据存储之文件内容存储(内部文件存储包括默认的文件存储、缓存文件存储)
- * 通过context对象获取文件路径
- * context.getCacheDir();
- * context.getFilesDir();
- * //操作文件的模式:如果需要多种操作模式,可对文件模式进行相加
- //int MODE_PRIVATE 私有模式
- //int MODE_APPEND 追加模式
- //int MODE_WORLD_READABLE 可读
- //int MODE_WORLD_WRITEABLE 可写
- */
- public class MainActivity extends Activity {
- private EditText editText ;
- private Button button ;
- private FileService fileService;
- private final String IMAGEPATH ="http://b.hiphotos.baidu.com/zhidao/pic/item/738b4710b912c8fcda0b7362fc039245d78821a0.jpg";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- fileService = new FileService(this);
- button = (Button) findViewById(R.id.button1);
- editText = (EditText) findViewById(R.id.editText1);
- //增加按钮点击监听事件
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String info = editText.getText().toString().trim();
- boolean flag = fileService.SaveContentToFile("info.txt", Context.MODE_APPEND, info.getBytes());
- if(flag){
- Toast.makeText(MainActivity.this, "保存文件成功", 0).show();
- }
- //网络下载图片存储之本地
- // MyTask task = new MyTask();
- // task.execute(IMAGEPATH);
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- //自定义异步任务,用于图片下载
- public class MyTask extends AsyncTask<String, Integer, byte[]>{
- @Override
- protected byte[] doInBackground(String... params) {
- HttpClient httpClient = new DefaultHttpClient();
- HttpGet httpGet = new HttpGet(params[0]);
- InputStream inputStream = null ;
- byte[] result = null;
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- try {
- //执行连接从response中读取数据
- HttpResponse response = httpClient.execute(httpGet);
- int leng = 0 ;
- byte [] data = new byte[1024] ;
- if (response.getStatusLine().getStatusCode() == 200) {
- inputStream = response.getEntity().getContent();
- while((leng = inputStream.read(data)) != 0) {
- byteArrayOutputStream.write(data, 0, leng);
- }
- }
- result = byteArrayOutputStream.toByteArray();
- fileService.SaveContentToFile("info.txt", Context.MODE_APPEND, result);
- } catch (Exception e) {
- e.printStackTrace();
- }finally{
- //关连接
- httpClient.getConnectionManager().shutdown();
- }
- return result;
- }
- }
- }
文件读写工具类Utils
- package com.example.android_data_storage_internal.file;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import android.content.Context;
- /**
- * @author xiaowu
- * @NOTE android文件读写帮助类
- */
- public class FileService {
- private Context context;
- public FileService(Context context) {
- this.context = context;
- }
- // fileName:文件名 mode:文件操作权限
- /**
- * @param fileName
- * 文件名
- * @param mode
- * 文件操作权限
- * @param data
- * 输出流读取的字节数组
- * @return
- */
- public boolean SaveContentToFile(String fileName, int mode, byte[] data) {
- boolean flag = false;
- FileOutputStream fileOutputStream = null;
- try {
- //通过文件名以及操作模式获取文件输出流
- fileOutputStream = context.openFileOutput(fileName, mode);
- fileOutputStream.write(data, 0, data.length);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (fileOutputStream != null) {
- try {
- fileOutputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- return flag;
- }
- /**
- * @param fileName
- * 文件名称
- * @return 文件内容
- */
- public String readContentFromFile(String fileName) {
- byte[] result = null;
- FileInputStream fileInputStream = null;
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- try {
- fileInputStream = context.openFileInput(fileName);
- int len = 0;
- byte[] data = new byte[1024];
- while ((len = fileInputStream.read(data)) != -1) {
- outputStream.write(data, 0, len);
- }
- result = outputStream.toByteArray();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- outputStream.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return new String(result);
- }
- /**
- * @param fileName 文件名称
- * @param mode 文件权限
- * @param data 输出流读取的字节数组
- * @return 是否成功标识
- */
- public boolean saveCacheFile(String fileName, byte[] data) {
- boolean flag = false;
- //通过context对象获取文件目录
- File file = context.getCacheDir();
- FileOutputStream fileOutputStream = null;
- try {
- File foder = new File(file.getAbsolutePath()+"/txt");
- if( !foder.exists() ){
- foder.mkdir(); //创建目录
- }
- fileOutputStream = new FileOutputStream(foder.getAbsolutePath()+"/"+fileName);
- fileOutputStream.write(data, 0, data.length);
- // context.openFileOutput("info.txt",
- // Context.MODE_PRIVATE);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (fileOutputStream != null) {
- fileOutputStream.close();
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println(file.getAbsolutePath());
- return flag;
- }
- /**
- * 获取android内存文件夹下的文件列表
- * @param path
- * @return
- */
- public File[] listFileDir(String path){
- //获取目录
- File file = context.getFilesDir();
- // System.out.println("-->CacheDir"+context.getCacheDir());
- // /data/data/com.example.android_data_storage_internal/cache
- // System.out.println("-->FilesDir"+file);
- // /data/data/com.example.android_data_storage_internal/files
- File root = new File(file.getAbsolutePath()+"/"+path);
- File[] listFiles = root.listFiles();
- return listFiles;
- }
- }
Junit单元测试类:
- package com.example.android_data_storage_internal;
- import android.content.Context;
- import android.test.AndroidTestCase;
- import android.util.Log;
- import com.example.android_data_storage_internal.file.FileService;
- /**
- * @author xiaowu
- * @note 单元测试类
- *
- */
- public class MyTest extends AndroidTestCase {
- private final String TAG = "MyTest";
- public void save() {
- FileService fileService = new FileService(getContext());
- //操作文件的模式:如果需要多种操作模式,可对文件模式进行相加
- //int MODE_PRIVATE 私有模式
- //int MODE_APPEND 追加模式
- //int MODE_WORLD_READABLE 可读
- //int MODE_WORLD_WRITEABLE 可写
- boolean flag = fileService.SaveContentToFile("login.txt", Context.MODE_PRIVATE,
- "你好".getBytes());
- Log.i(TAG, "-->"+flag);
- }
- public void read(){
- FileService fileService = new FileService(getContext());
- String msg = fileService.readContentFromFile("info.txt");
- Log.i(TAG, "--->"+msg);
- }
- public void test(){
- FileService fileService = new FileService(getContext());
- fileService.saveCacheFile("my.txt","小五".getBytes());
- }
- public void test2(){
- FileService fileService = new FileService(getContext());
- fileService.listFileDir("my.txt");
- }
- }
清单文件:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android_data_storage_internal"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="18" />
- <instrumentation
- android:name="android.test.InstrumentationTestRunner"
- android:targetPackage="com.example.android_data_storage_internal" >
- </instrumentation>
- <!-- 增加用户访问网络权限 -->
- <uses-permission android:name="android.permission.INTERNET"/>
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <!-- 引入用与Junit测试包 -->
- <uses-library android:name="android.test.runner" android:required="true"/>
- <activity
- android:name="com.example.android_data_storage_internal.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
android 开发-数据存储之文件存储的更多相关文章
- IOS开发--数据持久化篇文件存储(二)
前言:个人觉得开发人员最大的悲哀莫过于懂得使用却不明白其中的原理.在代码之前我觉得还是有必要简单阐述下相关的一些知识点. 因为文章或深或浅总有适合的人群.若有朋友发现了其中不正确的观点还望多多指出,不 ...
- Android开发--数据存储之File文件存储
转载来自:http://blog.csdn.net/ahuier/article/details/10364757,并进行扩充 引言:Android开发中的数据存储方式 Android提供了5种方式存 ...
- 关于Android开发数据存储的方式(一)
关于Android开发数据存储方式(一) 在厦门做Android开发也有两个月了,快情人节了.我还在弄代码. 在微信平台上开发自己的APP,用到了数据存储的知识,如今总结一下: 整体的来讲.数据存储方 ...
- Android开发之获取xml文件的输入流对象
介绍两种Android开发中获取xml文件的输入流对象 第一种:通过assets目录获取 1.首先是在Project下app/src/main目录下创建一个assets文件夹,将需要获取的xml文件放 ...
- Android开发手记(17) 数据存储二 文件存储数据
Android为数据存储提供了五种方式: 1.SharedPreferences 2.文件存储 3.SQLite数据库 4.ContentProvider 5.网络存储 本文主要介绍如何使用文件来存储 ...
- android开发中的5种存储数据方式
数据存储在开发中是使用最频繁的,根据不同的情况选择不同的存储数据方式对于提高开发效率很有帮助.下面笔者在主要介绍Android平台中实现数据存储的5种方式. 1.使用SharedPreferences ...
- Android 数据存储之 文件存储
-------------------------------------------文件存储----------------------------------------------- 文件存储是 ...
- Android数据存储之文件存储
首先给大家介绍使用文件如何对数据进行存储,Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的. public ...
- android 开发-数据存储之共享参数
android提供5中数据存储方式 数据存储之共享参数 内部存储 扩展存储 数据库存储 网络存储 而共享存储提供一种可以让用户存储保存一些持久化键值对在文件中,以供其他应用对这些共享参数进行调用.共 ...
随机推荐
- 【转】Jquery折叠效果
转自:http://www.cnblogs.com/clc2008/archive/2011/10/25/2223254.html <!DOCTYPE html PUBLIC "-// ...
- js遍历for,forEach, for in,for of
ECMAScript5(es5)有三种for循环 简单for for in forEach ECMAScript6(es6)新增 for of 简单for for是循环的基础语法,也是最常用的循环结构 ...
- <正则吃饺子> :关于使用pd创建表时需要注意的地方
公司项目使用pd设计数据库表.之前用过,但是年代比较久远了,有些细节忘记了,今天重新使用时候,生疏了,现在稍微记录下吧. 1.pd创建表的使用,可以直接从网上搜索,博文比较多,如 “pd 设计数据库表 ...
- JavaScript高级程序设计学习笔记第十五章--使用Canvas绘图
一.基本用法 1.要使用<canvas>元素,必须先设置其 width 和 height 属性,指定可以绘图的区域大小.能通过 CSS 为该元素添加样式,如果不添加任何样式或者不绘制任何图 ...
- Hadoop的namenode和secondnamenode分开部署在不同服务器
一.系统环境: Hadoop 0.20.2.JDK 1.6.Linux操作系统 二.使用背景 网上关于Hadoop的集群配置,很多情况下,都是把namenode和secondnamenode部署在 ...
- webAPI中使用log4net进行日志记录
1.从nuget下载log4net 2.根据需求配置web.config,或者另外写一个log4net.config文件,各个节点的意义详细查询api <section name="l ...
- 滴水穿石 C#中多线程 委托的使用
什么是多线程?我们在建立以个C#项目时,往往会在Form1上添加控件,然后写代码,初 学者都是在重复这个过程,其实这个过程是单线程的,可以理解为只有“main”主线程,有 的时候往往需要同时测量多个东 ...
- DESede/CBC/PKCS5Padding
Java.security.NoSuchAlgorithmException: Cannot find any provider supporting DESede/CBC/PKCS5Padding ...
- Ubuntu使用技巧
命令 获取系统安装包的编译源码及脚本 apt-get source package 查询端口被占用的进程 lsof -i:端口号 配置 配置阿里源 # mv /etc/apt/source.list ...
- bbc--平台点击进入详情页配置
路径: 配置方式: $finderview = 'detail_base'; $arr = array( 'app'=>$_GET['app'], 'ctl'=>$_GET['ctl'], ...