Android进阶(七)数据存储
Android 数据存储
1访问资源文件
直接将文件保存在设备的内部存储. 默认情况下,保存到内部存储的文件为私有的,其他应用程序不能访问它们,当用户卸载应用程序时,所保存的文件也一并删除。
1.1访问静态应用程序文件-只读
1.1.1从resource中的res/raw文件夹中获取文件
保存静态文件, 通过openRawResource()传入资源ID( R.raw.<filename> ID),返回InputStream读取文件,该文件不能用于更新操作。
示例:
String res = "";
try{
InputStream in = getResources().openRawResource(R.raw.bbi);
//在\Test\res\raw\bbi.txt,
int length = in.available();
byte [] buffer = new byte[length];
in.read(buffer);
//res = EncodingUtils.getString(buffer, "UTF-8");
//res = EncodingUtils.getString(buffer, "UNICODE");
res = EncodingUtils.getString(buffer, "BIG5");
//依bbi.txt的编码类型选择合适的编码,如果不调整会乱码
in.close();
}catch(Exception e){
e.printStackTrace();
}
//把得到的内容显示在TextView上
myTextView.setText(res);
1.1.2从asset中获取文件并读取数据(资源文件只能读不能写)
assets目录下,称为原生文件,这类文件在被打包成apk文件时是不会进行压缩的,android使用AssetManager对assets文件进行访问,通过getResources().getAssets()获得AssetManager,
其有一个open()方法可以根据用户提供的文件名,返回一个InputStream对象供用户使用。
eg:
//文件名字
String fileName = "yan.txt";
String res="";
try{
// \Test\assets\yan.txt这里有这样的文件存在
//通过getResources().getAssets()获得AssetManager
InputStream in = getResources().getAssets().open(fileName);
//返回读取的大概字节数
int length = in.available();
byte [] buffer = new byte[length];
in.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
}catch(Exception e){
e.printStackTrace();
}
1.2访问设备存储相当于API工作目录
1.2.1调用context.openFileInput() 返回 FileInputStream读文件
1.2.2通过调用context.openFileOutput() 返回FileOutputStream写文件
//写文件在./data/data/com.tt/files/下面
openFileOutput()参数
filename 文件名
int mode 操作模式 MODE_PRIVATE 默认,创建或替换该文件名的文件作为应用程序私有文件。
MODE_APPEND,MODE_WORLD_READABLE , MODE_WORLD_WRITEABLE,
eg:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
1.3保存缓存文件
如果您想缓存一些数据,而不是它长期存放,可以把文件保存为缓存文件;保存为缓存文件时,当设备内部存储空间不足,系统可能会删除这些缓存文件恢复空间;我们应该限制缓存空间的大小;
当用户卸载应用程序时,这些文件将被删除。
使用方法:
//获取保存文件系统的目录绝对路径
getFilesDir();
//在存储空间中创建或打开一个目录
getDir();
//删除存储文件
deleteFile();
//返回应用程序保存文件列表
fileList();
2使用外部存储
2.1.1检测外部存储状态:
Environment.getExternalStorageState()
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
2.1.2访问外部存储
API8以上,使用getExternalFilesDir()打开一个外部存储文件目录,这个方法需传递一个指定类型目录的参数,如:DIRECTORY_MUSIC和DIRECTORY_RINGTONES,为空返回应用程序文件根目录;
此方法可以根据指定的目录类型创建目录,该文件为应用程序私有,如果卸载应用程序,目录将会一起删除。
API7一下,使用getExternalStorageDirectory(), 打开外部存储文件根目录 ,你的文件写入到如下目录中:/Android/data/<package_name>/files/
eg:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
file.delete();
}
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
if (file != null) {
return file.exists();
}
return false;
}
2.1.3保存为共享文件
如果想将文件保存为不为应用程序私有,在应用程序卸载时不被删除,需要将文件保存到外部存储的公共目录上,这些目录在存储设备根目录下;如:音乐,图片,铃声等。
API8以上,使用 getExternalStoragePublicDirectory(),传入一个公共目录的类型参数,如DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES等, 目录不存在时这个方法会为你创建目录。
API7一下,使用 getExternalStorageDirectory() 打开存储文件根目录,保存文件到下面的目录中:
Music,Podcasts,Ringtones,Alarms,Notifications,Pictures,Movies,Download。
eg:
void createExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user's public pictures directory.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user's
// public pictures directory and delete the file. If external
// storage is not currently mounted this will fail.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
file.delete();
}
boolean hasExternalStoragePublicPicture() {
// Create a path where we will place our picture in the user's
// public pictures directory and check if the file exists. If
// external storage is not currently mounted this will think the
// picture doesn't exist.
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
return file.exists();
}
2.1.4保存缓存文件
API8以上,使用getExternalCacheDir() 打开存储目录保存文件,如卸载应用程序,缓存文件将自动删除,在应用程序运行期间你可以管理这些缓存文件,如不在使用可以删除以释放空间。
API7以下,使用getExternalStorageDirectory() 打开缓存目录,缓存文件保存在下面的目录中:
/Android/data/<package_name>/cache/
<package_name> 你的java包名如 "com.example.android.app".
2.1.5读写文件
提示:openFileOutput是在raw里编译过的访问设备存储,FileOutputStream是任何文件都可以
访问sdcard直接实例FileOutputStream对象,而访问存储设备文件通过openFileOutput返回FileOutputStream对象对数据操作。
2.1.6 sdcard中去读文件
示例:
String fileName = "/sdcard/Y.txt";
//也可以用String fileName = "mnt/sdcard/Y.txt";
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
//FileInputStream fin = openFileInput(fileName);
//用这个就不行了,必须用FileInputStream
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}catch(Exception e){
e.printStackTrace();
}
myTextView.setText(res);
2.1.7 SDCard中写文件
般写在\data\data\com.test\files\里面,打开DDMS查看file explorer是可以看到仿真器文件存放目录的结构的
String fileName = "TEST.txt";
String message = "FFFFFFF11111FFFFF" ;
writeFileData(fileName, message);
public voidwriteFileData(String fileName,String message){
try{
FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);
byte [] bytes = message.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
2.1.8 写,读sdcard目录上的文件,要用FileOutputStream, 不能用openFileOutput
//写在/mnt/sdcard/目录下面的文件
public voidwriteFileSdcard(String fileName,String message){
try{
//FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
FileOutputStream fout = new FileOutputStream(fileName);
byte [] bytes = message.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//读在/mnt/sdcard/目录下面的文件
public String readFileSdcard(String fileName){
String res="";
try{
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
3android读写文件正确实行方法
Android读写文件正确实行方法介绍
http://www.ehuait.com/skill/android/2011-09-08/1445.html
众所周知Android有一套自己的安全模型, 具体可参见Android开发文档。当应用程序(.apk)在安装时就会分配一个userid,当该应用要去访问其他资源比如文件的时候,就需要userid匹配。
默认情况下,任何应用创建的文件,数据库,sharedpreferences都应该是私有的(位于/data/data/your_project/files/),其余程序无法访问。
除非在创建时指明是MODE_WORLD_READABLE 或者 MODE_WORLD_WRITEABLE,只要这样其余程序才能正确访问。
因为有这种Android读写文件的方法在安全上有所保障,进程打开文件时Android要求检查进程的user id。所以不能直接用java的api来打开,因为java的io函数没有提这个机制 。
无法用java的api直接打开程序私有的数据 ,默认路径为/data/data/your_project/files/
1.FileReader file = new FileReader("Android.txt"); 这里特别强调私有数据!言外之意是如果某个文件或者数据不是程序私有的,即访问它时无须经过Android的权限检查,那么还是可以用java的io api来直接访问的。
所谓的非私有数据是只放在sdcard上的文件或者数据,可以用java的io api来直接打开sdcard上文件。
1.FileReader file = new FileReader("/sdcard/Android.txt"); 如果要打开程序自己私有的文件和数据,那必须使用Activity提供openFileOutput和openFileInput方法。
创建程序私有的文件,由于权限方面的要求,必须使用activity提供的Android读写文件方法
1.FileOutputStream os = this.openFileOutput("Android.txt", MODE_PRIVATE);
2.OutputStreamWriter outWriter = new OutputStreamWriter (os);
读取程序私有的文件,由于权限方面的要求,必须使用activity提供的方法
1.FileInputStream os =this.openFileInput("Android.txt");
2.InputStreamReader inReader = new InputStreamReader(os);
4Shared Preferences用户首选项
主要用于存放软件的配置参数等信息。sharedPreferences用于存取和修改软件配置参数数据的接口。存放键值对,保存用户个人首选项信息,比如喜爱音乐,主题,首选Activity等
4.1.1使用getSharedPrefernces()
使用步骤:
存放:
1.获得SharedPreferences 的实例对象,通过getSharedPreferences()传递文件名和模式;
2.获得Editor 的实例对象,通过SharedPreferences 的实例对象的edit()方法;
3.存入数据,利用Editor 对象的putXXX()方法;
4.提交修改的数据,利用Editor 对象的commit()方法。
读取:
1.获得SharedPreferences 的实例对象,通过getSharedPreferences()传递文件名和模式;
2.读取数据,通过SharedPreferences 的实例对象的getXXX()方法。
eg:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
4.1.2 getPreferences()
Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
Android进阶(七)数据存储的更多相关文章
- 67.Android中的数据存储总结
转载:http://mp.weixin.qq.com/s?__biz=MzIzMjE1Njg4Mw==&mid=2650117688&idx=1&sn=d6c73f9f04d0 ...
- Android Learning:数据存储方案归纳与总结
前言 最近在学习<第一行android代码>和<疯狂android讲义>,我的感触是Android应用的本质其实就是数据的处理,包括数据的接收,存储,处理以及显示,我想针对这几 ...
- Android中的数据存储
Android中的数据存储主要分为三种基本方法: 1.利用shared preferences存储一些轻量级的键值对数据. 2.传统文件系统. 3.利用SQLite的数据库管理系统. 对SharedP ...
- Android五种数据存储方式
android 五种数据存储 :SharePreferences.SQLite.Contert Provider.File.网络存储 Android系统提供了四种存储数据方式.分别为:SharePre ...
- Android中的数据存储(二):文件存储 2017-05-25 08:16 35人阅读 评论(0) 收藏
文件存储 这是本人(菜鸟)学习android数据存储时接触的有关文件存储的知识以及本人自己写的简单地demo,为初学者学习和使用文件存储提供一些帮助.. 如果有需要查看SharedPreference ...
- Android下的数据存储与訪问 --- 以文件的形式
Android下的数据存储与訪问 --- 以文件的形式 1.1 储存文件存放在手机内存中: // *** 储存数据到 /data/data/包名/files/jxn.txt文件里 String dat ...
- Android——几种数据存储应用浅谈
(1)android中的数据存储主要有五种方式: 第一种.sharedPreferences存储数据, 适用范围:保存少量的数据,且这些数据的格式非常简单:字符串型.基本类型的值.比如应用程序的各种配 ...
- Android之网络数据存储
一.网络保存数据介绍 可以使用网络来保存数据,在需要的时候从网络上获取数据,进而显示在App中. 用网络保存数据的方法有很多种,对于不同的网络数据采用不同的上传与获取方法. 本文利用LeanCloud ...
- Android之文件数据存储
一.文件保存数据介绍 Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的.文件可用来存放大量数据,如文本.图 ...
随机推荐
- Mysql锁机制--行锁
Mysql 系列文章主页 =============== 1 准备数据 1.1 建表 DROP TABLE IF EXISTS employee; CREATE TABLE IF NOT EXISTS ...
- java new 关键字到底做了什么?
一.关键字new概述 "new"可以说是Java开发者最常用的关键字,我们使用new创建对象,使用new并通过类加载器来实例化任何我们需要的东西,但你是否深入了解过new在编译的瞬 ...
- 用JavaScript按一定格式解析出URL 串中所有的参数
1.先看看location对象 2.其中的search属性就获取当前URL的查询部分(问号?之后的部分) 3.改造location.search 比如当前URL为:https://www.hao123 ...
- Java锁Synchronized对象锁和类锁区别
java的内置锁:每个java对象都可以用做一个实现同步的锁,这些锁成为内置锁.线程进入同步代码块或方法的时候会自动获得该锁,在退出同步代码块或方法时会释放该锁.获得内置锁的唯一途径就是进入这个锁的保 ...
- JAVA 面试基础
经典的Java基础面试题________________________________________________________________________________________ ...
- centos 挂载ntfs格式的移动硬盘
经查找资料发现,linux也是可以支持ntfs格式分区的,只是需要安装ntfs-3g插件. CentOS挂载ntfs移动硬盘的具体步骤: 1 安装fuse. 下载fuse-2.9.3.tar.gz ...
- python学习之路网络编程篇(第四篇)- 续
Memcache简介 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速 ...
- C#系统之垃圾回收
1. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syste ...
- Go 语言递归函数
递归,就是在运行的过程中调用自己. 语法格式如下: func recursion() { recursion() /* 函数调用自身 */ } func main() { recursion() } ...
- Android简易实战教程--第四十九话《满屏拖动的控件》
今天做个有意思的效果吧,控件的拖拽,简单实用,逻辑清晰点3分钟看完. 说的很高大上,其实就是拖动Button按钮跟着鼠标位置满手机屏幕跑罢了. 直接上简单的代码吧: public class Main ...