Android五种数据存储(数据持久化)方式

1、sharedpreference 共享参数(一般用于保存用户设置偏好);
**
* 特点:
* (1)以键值对的形式保存到data/data/应用程序包名/shared_prefs目录的XXX.xml文件中
* (2)目前支持的数据类型有String int float boolean long
* (3)不支持自定义的Object
* (4)通常用来存储App上的用户配置信息.如:是否震动,是否打开背景音乐 小游戏积分 用户账号密码信息
* @author Administrator
*
*/
2、用法:Sharedpreferences对象的几种获取方式:
//获取SharedPreferences对象的方式之一:
/**
* 2个参数
* 1.name:要存储的SharedPreferences文件的文件名
* 2.mode:操作模式,对文件的操作权限
* MODE_PRIVATE:默认的操作模式,表示该SharedPreferences文件的数据只能被当前的应用程序读写.当指定同样文件名的时候,新写入的内容会覆盖原文件的内容
* MODE_APPEND:如果该文件已存在,不会创建新文件,而是往源文件里追加内容
* MODE_MULTI_PROCESS:用于会有多个进程对同一个SharedPreferences文件进行读写
*/
// sp = getSharedPreferences("myInfo", MODE_PRIVATE);
//获取SharedPreferences对象的方式之二:
//该方法会将当前Activity的类名作为该SharedPreferences文件的文件名即MainActivity.xml
// sp = getPreferences(MODE_PRIVATE);
//获取SharedPreferences对象的方式之三:
//该方法会将当前应用程序的包名最为前缀来给SharedPreferences文件命名
//例如:com.qianfeng.day12_sharedpreferences_preferences.xml
sp = PreferenceManager.getDefaultSharedPreferences(this);
数据保存方式:
//得到一个编辑器对象
Editor editor = sp.edit();
editor.putString("userName", editText_name.getText().toString().trim());
editor.putString("userPassword", editText_password.getText().toString().trim());
editor.putBoolean("isGirl", false);
editor.putInt("userAge", 22);
//提交保存
boolean bl = editor.commit();
//取出数据
public void getInfo(View view){

String name = sp.getString("userName", "");
String password = sp.getString("userPassword", "");
Boolean isGirl = sp.getBoolean("isGirl", false);
int age = sp.getInt("userAge", 18);
Toast.makeText(MainActivity.this, "账号:"+name+",密码:"+password+",isGirl:"+isGirl+",年龄:"+age, Toast.LENGTH_LONG).show();
}

二、Internal Storage(内部存储器)
特点:**
* Context context:上下文
* KFC广告词:we do chicken right
* Context:就是一个类 提供一些方便的API 得到应用程序的环境,应用程序包名 安装路径 文件路径 资源资产路径...
*
* Internal Storage特点:
* 1.内部存储总是可用的
* 2.内部存储的文件默认只能被当前应用程序访问,它是私有的
* 3.如果App卸载,内部存储文件也会被删除
* 4.如果文件只提供给当前的应用程序访问,那么放到内部存储中比较合适
* 5.内部存储器的读取速度最快且内部存储空间十分珍贵,开发中需要合理使用
*
*/
两种存储位置:
/**
* 保存路径:/data/data/包名/cache 不是很重要的数据或者临时性的数据可以放在这里
* getCacheDir() 获取内部存储cache目录的绝对路径
*/
//保存数据到内部存储的Cache目录
public void saveInfo(View view){
String content = editText_name.getText().toString().trim()+":"+editText_phone.getText().toString().trim();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
/**
* 保存路径:/data/data/包名/cache 不是很重要的数据或者临时性的数据可以放在这里
* getCacheDir() 获取内部存储cache目录的绝对路径
*/
try {
fos = new FileOutputStream(new File(context.getCacheDir(),"LoginInfo"));
bos = new BufferedOutputStream(fos);
bos.write(content.getBytes());
bos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//从内部存储的Cache目录取出数据
public void getInfo(View view){
FileInputStream fis = null;
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
File file = new File(getCacheDir(),"LoginInfo");
if (file.exists()) {
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = bis.read(buffer))!=-1) {
baos.write(buffer, 0, len);
baos.flush();
}
Toast.makeText(MainActivity.this, baos.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
baos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//清除缓存(内部存储缓存目录下的文件)
public void clearCache(View view){
File file = new File(getCacheDir(),"LoginInfo");
if (file.exists()) {
boolean bl = file.delete();
if (bl) {
Toast.makeText(MainActivity.this, "清除缓存成功", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "清除缓存失败", Toast.LENGTH_SHORT).show();
}
}
}

//点击按钮保存数据到内部存储的files目录
Context.getFilesDir():获取内部存储的files目录的绝对路径
context.openFileInput("name"):打开内部存储files目录下的文件,返回一个输入流对象
* context.openFileOutput("name",mode):打开内部存储files目录下的文件进行写入,返回一个输出流对象(如果文件不存在就自动创建一个)
//点击按钮保存数据到内部存储的files目录
public void saveInfo(View view){
String content = editText_name.getText().toString().trim()+":"+editText_phone.getText().toString().trim();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos= openFileOutput("MyLoginInfo", MODE_PRIVATE|MODE_APPEND);
bos = new BufferedOutputStream(fos);
bos.write(content.getBytes());
bos.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//从内部存储的files目录取出数据
public void getInfo(View view){
FileInputStream fis = null;
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
fis = openFileInput("MyLoginInfo");
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = bis.read(buffer))!= -1) {
baos.write(buffer, 0, len);
baos.flush();
}
Toast.makeText(MainActivity.this, baos.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
baos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*
三、External Storage(外部存储)
/**
* External Storage:外部存储
* 1.外部存储不见得总是可用的: 例如:SD卡被移除了
* 2.外部存储是全局可见的,存放到外部存储中的文件可以被当前设备中所有能够操作该文件的app访问
* 3.为了更好的管理外部存储,Android系统进行了更细致的划分:公共的外部存储和私有的外部存储,当app卸载的时候
* 公共的外部存储中的文件不会被删除,私有外部存储的文件会被删除
* 4.如果你当前文件需要分享给其它的app访问或者使用,文件需要长久保存,文件比较大,或者文件的安全性不做具体要求时,可以考虑使用外部存储
*
* @author Administrator
*
*/
// 获取SD卡公有目录的路径(9大公有目录)(只要可以调用这个 资源的app都可以访问)
public static String getSDCardPublicDir(String type) {
return Environment.getExternalStoragePublicDirectory(type).toString();
}

// 获取SD卡私有Cache目录的路径(通过上下文获取,因为它属于一个application私有的)
public static String getSDCardPrivateCacheDir(Context context) {
return context.getExternalCacheDir().getAbsolutePath();
}

// 获取SD卡私有Files目录的路径(10大私有目录)
public static String getSDCardPrivateFilesDir(Context context, String type) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
public class SDCardHelper {

// 判断SD卡是否被挂载
public static boolean isSDCardMounted() {
// return Environment.getExternalStorageState().equals("mounted");
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}

// 获取SD卡的根路径
public static String getSDCardBaseDir() {
if (isSDCardMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return "";
}

// 获取SD卡的完整空间大小,返回MB
public static long getSDCardSize() {
if (isSDCardMounted()) {
StatFs statFs = new StatFs(getSDCardBaseDir());
long count = statFs.getBlockCount();
long size = statFs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;
}

// 获取SD卡剩余空间大小,返回MB
public static long getSDCardFreeSize() {
if (isSDCardMounted()) {
StatFs statFs = new StatFs(getSDCardBaseDir());
long count = statFs.getFreeBlocks();
long size = statFs.getBlockSize();
return count * size / 1024 / 1024;
}
return 0;

}

// 获取SD卡的可用空间大小,返回MB
public static long getSDCardAvailableSize() {
if (isSDCardMounted()) {
StatFs statFs = new StatFs(getSDCardBaseDir());
long count = statFs.getAvailableBlocks();
long size = statFs.getBlockSize();
return count * size / 1024 / 1024;

}
return 0;

}

// 往SD卡的公有目录下保存文件
public static boolean saveFileToSDCardPublicDir(byte[] data, String type,
String fileName) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = Environment
.getExternalStoragePublicDirectory(type);
Log.i("SDCardHelper", "------>" + file.getAbsolutePath());
try {
fos = new FileOutputStream(new File(file, fileName));
bos = new BufferedOutputStream(fos);
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return false;

}

// 往SD卡的私有Files目录下保存文件
public static boolean saveFileToSDCardPrivateFilesDir(byte[] data,
String type, String fileName, Context context) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = context.getExternalFilesDir(type);
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return false;

}

// 往SD卡的私有Cache目录下保存文件
public static boolean saveFileToSDCardPrivateCacheDir(byte[] data,
String fileName, Context context) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = context.getExternalCacheDir();
try {
bos = new BufferedOutputStream(new FileOutputStream(new File(
file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return false;

}

// 往SD卡的自定义目录下保存文件
public static boolean saveFileToSDCardCustomDir(byte[] data, String dir,
String fileName) {
BufferedOutputStream bos = null;
if (isSDCardMounted()) {
File file = new File(getSDCardBaseDir() + File.separator + dir);
if (!file.exists()) {
file.mkdirs();
try {
bos = new BufferedOutputStream(new FileOutputStream(
new File(file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

return false;

}

// 从SD卡获取文件
public static byte[] loadFileFromSDCard(String filePath) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
bis = new BufferedInputStream(new FileInputStream(
new File(filePath)));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = bis.read(buffer)) != -1) {
baos.write(buffer, 0, len);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

return null;

}

// 获取SD卡公有目录的路径(9大公有目录)
public static String getSDCardPublicDir(String type) {
return Environment.getExternalStoragePublicDirectory(type).toString();
}

// 获取SD卡私有Cache目录的路径
public static String getSDCardPrivateCacheDir(Context context) {
return context.getExternalCacheDir().getAbsolutePath();
}

// 获取SD卡私有Files目录的路径(10大私有目录)
public static String getSDCardPrivateFilesDir(Context context, String type) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
// 判断指定路径下的文件是否存在
public static boolean isFileExist(String filePath) {
File file = new File(filePath);
return file.isFile();
}

// 从sdcard中删除文件
public static boolean removeFileFromSDCard(String filePath) {
File file = new File(filePath);
if (file.exists()) {
try {
file.delete();
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值