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中数据存储方式 数据存储之共享参数 内部存储 扩展存储 数据库存储 网络存储 而共享存储提供一种可以让用户存储保存一些持久化键值对在文件中,以供其他应用对这些共享参数进行调用.共 ...
随机推荐
- Java访问子类对象的实例变量
对于Java这种语言来说,一般来说,子类可以调用父类中的非private变量,但在一些特殊情况下, Java语言可以通过父类调用子类的变量 具体的还是请按下面的例子吧! package com.yon ...
- mysql--事务demo1----
package com.etc.entity; import java.sql.Connection; import java.sql.PreparedStatement; import java.s ...
- python并发编程之多进程1互斥锁与进程间的通信
一.互斥锁 进程之间数据隔离,但是共享一套文件系统,因而可以通过文件来实现进程直接的通信,但问题是必须自己加锁处理. 注意:加锁的目的是为了保证多个进程修改同一块数据时,同一时间只能有一个修改,即串行 ...
- 报错apachectl restart
httpd not running, trying to start(98)Address already in use: make_sock: could not bind to address [ ...
- java多线程无锁和工具类
1 无锁 (1) cas (compare and swap) 设置值的时候,会比较当前值和当时拿到的值是否相同,如果相同则设值,不同则拿新值重复过程:注意,在设置值的时候,取值+比较+设值 是一条c ...
- DOS查看端口占用及杀掉进程命令
转载自:http://www.cnblogs.com/rainman/p/3457227.html 1. 查看端口占用 在windows命令行窗口下执行: netstat -aon|findstr & ...
- IPv4 和 IPv6地址
目前Internet上使用的基本都是IPv4地址,也就是说地址总共是32个比特位,也就是32位二进制数. 所以IPv4地址总的容量是 2的32次方 = 4294967296 比如 11010010 ...
- 7.26实习培训日志-Oracle SQL(二)
Oracle SQL(二) 条件表达式 CASE 语句 或者DECODE 函数,两者均可实现 IF-THEN-ELSE 的逻辑,相比较而言,DECODE 更加简洁 SELECT last_name , ...
- ES Docs-2:Exploring ES cluster
The REST API Now that we have our node (and cluster) up and running, the next step is to understand ...
- 未能加载文件或程序集“Oracle.DataAccess, Version=4.112.2.0, Culture=neutral, PublicKeyTok”
1.首先看一下C:\Windows\assembly目录下是不是只有一个Oracle.DataAccess,我的版本是10,如果是只有一个,则往下看: 2.将完整的odp.net(目录下包含注册文件) ...