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. Python-实现与metasploit交互并进行ms17_010攻击

    关于ms17_010,可参考http://www.cnblogs.com/sch01ar/p/7672454.html 目标IP:192.168.220.139 本机IP:192.168.220.14 ...

  2. TP5隐藏url中的index.php

    在public文件夹下,有个.htacess文件,没有则新建一个, 如果已有这个文件,原文件内容如下: <IfModule mod_rewrite.c> Options +FollowSy ...

  3. phpstorm断点调试 php.ini 文件中 Xdebug 配置

    [XDebug]xdebug.profiler_output_dir="D:\phpStudy\tmp\xdebug"xdebug.trace_output_dir="D ...

  4. LAMP 1.2 Apache编译安装问题解决

    这个错误安装 yum install -y gcc error: mod_deflate has been requested but can not be built due to prerequi ...

  5. ABCD四个人说真话的概率都是1/3。假如A声称B否认C说D是说谎了,那么D说过的那句话真话的概率是多少

    ABCD四个人说真话的概率都是1/3.假如A声称B否认C说D是说谎了,那么D说过的那句话 真话的概率是多少 记"A声称B否认C说D说谎"为X,那么由贝叶斯公式,所求的 P(D真)P ...

  6. macOS 安装 Docker

    系统要求 Docker for Mac 要求系统最低为 macOS 10.10.3 Yosemite,或者 2010 年以后的 Mac 机型,准确说是带 Intel MMU 虚拟化的,最低 4GB 内 ...

  7. 6.7 安装ant

    准备好安装包: 安装vim: 解压: tar -xzvf apahce-ant-1.10.1-bin.tar.gz 这里,我将apache-ant-1.10.1-bin.tar.gz复制并解压到了/h ...

  8. 解决Umbraco中Generated文件夹下面model问题

    在Visual Studio中开发Umbraco项目时,有一个文件夹叫Generated, 在Umbraco 的back office中的Document Type产生的model都会自动进入这个文件 ...

  9. 将一个mapList转换为beanList

    public static <T> List<T> copyMapToBean(   List<Map<String, Object>> resultM ...

  10. 输入类型<input type="number"> / input标签的输入限制

    输入限制 属性 描述 disabled 规定输入字段应该被禁用. max 规定输入字段的最大值. maxlength 规定输入字段的最大字符数. min 规定输入字段的最小值. pattern 规定通 ...