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 开发-数据存储之文件存储的更多相关文章

  1. IOS开发--数据持久化篇文件存储(二)

    前言:个人觉得开发人员最大的悲哀莫过于懂得使用却不明白其中的原理.在代码之前我觉得还是有必要简单阐述下相关的一些知识点. 因为文章或深或浅总有适合的人群.若有朋友发现了其中不正确的观点还望多多指出,不 ...

  2. Android开发--数据存储之File文件存储

    转载来自:http://blog.csdn.net/ahuier/article/details/10364757,并进行扩充 引言:Android开发中的数据存储方式 Android提供了5种方式存 ...

  3. 关于Android开发数据存储的方式(一)

    关于Android开发数据存储方式(一) 在厦门做Android开发也有两个月了,快情人节了.我还在弄代码. 在微信平台上开发自己的APP,用到了数据存储的知识,如今总结一下: 整体的来讲.数据存储方 ...

  4. Android开发之获取xml文件的输入流对象

    介绍两种Android开发中获取xml文件的输入流对象 第一种:通过assets目录获取 1.首先是在Project下app/src/main目录下创建一个assets文件夹,将需要获取的xml文件放 ...

  5. Android开发手记(17) 数据存储二 文件存储数据

    Android为数据存储提供了五种方式: 1.SharedPreferences 2.文件存储 3.SQLite数据库 4.ContentProvider 5.网络存储 本文主要介绍如何使用文件来存储 ...

  6. android开发中的5种存储数据方式

    数据存储在开发中是使用最频繁的,根据不同的情况选择不同的存储数据方式对于提高开发效率很有帮助.下面笔者在主要介绍Android平台中实现数据存储的5种方式. 1.使用SharedPreferences ...

  7. Android 数据存储之 文件存储

    -------------------------------------------文件存储----------------------------------------------- 文件存储是 ...

  8. Android数据存储之文件存储

    首先给大家介绍使用文件如何对数据进行存储,Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的. public ...

  9. android 开发-数据存储之共享参数

    android提供5中数据存储方式 数据存储之共享参数 内部存储 扩展存储 数据库存储 网络存储  而共享存储提供一种可以让用户存储保存一些持久化键值对在文件中,以供其他应用对这些共享参数进行调用.共 ...

随机推荐

  1. swift-get-nodes简单使用

    在参考http://blog.csdn.net/cywosp/article/details/12850645文章对对象的具体物理磁盘位置进行查找时,发现两个问题: 1. 在使用swift+keyst ...

  2. 网站跳转到Apache 2 Test Page powered by CentOS

    原来是80端口被占用的问题 解决80端口占用问题 sudo fuser -n tcp -k 覆盖原来的httpd cp /usr/local/apache2/bin/apachectl /etc/in ...

  3. MyBatis 学习总结(1)

    MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架,几乎消除了所有的 JDBC 代码和参数的手工设置以及结果集的处理,通过XML(sqlMapConfig)或注解配置数据源和 ...

  4. [hdu4734]F(x)数位dp

    题意:求0~f(b)中,有几个小于等于 f(a)的. 解题关键:数位dp #include<bits/stdc++.h> using namespace std; typedef long ...

  5. C++二叉树结构的建立和操作

    二叉树是数据结构中的树的一种特殊情况,有关二叉树的相关概念,这里不再赘述,如果不了解二叉树相关概念,建议先学习数据结构中的二叉树的知识点. 准备数据 定义二叉树结构操作中需要用到的变量及数据等. #d ...

  6. centos-6.4 yum EPEL

    初用centos,很多不习惯,记录一下. 首先装EPEL,不然默认的包少得可怜:(详见:http://www.rackspace.com/knowledge_center/article/instal ...

  7. 5、bam格式转为bigwig格式

    1.Bam2bigwig(工具) https://www.researchgate.net/publication/301292288_Bam2bigwig_a_tool_to_convert_bam ...

  8. p2371&bzoj2118 墨墨的等式

    传送门(bzoj) 题目 墨墨突然对等式很感兴趣,他正在研究a1x1+a2y2+…+anxn=B存在非负整数解的条件,他要求你编写一个程序,给定N.{an}.以及B的取值范围,求出有多少B可以使等式存 ...

  9. p3627&bzoj1179 抢掠计划(ATM)

    传送门(洛谷) 传送门(bzoj) 题目 Siruseri 城中的道路都是单向的.不同的道路由路口连接.按照法律的规定, 在每个路口都设立了一个 Siruser i 银行的 ATM 取款机.令人奇怪的 ...

  10. 阶段2-新手上路\项目-移动物体监控系统\Sprint2-摄像头子系统开发\第2节-V4L2图像编程接口深度学习

    参考资料: http://www.cnblogs.com/emouse/archive/2013/03/04/2943243.htmlhttp://blog.csdn.net/eastmoon5021 ...