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>