Android开发7:简单的数据存储(使用SharedPreferences)和文件操作,
前言
啦啦啦~大家好,又见面啦~
本篇博文讲和大家一起完成一个需要注册、登录的备忘录的,一起学习 SharedPreferences 的基本使用,学习 Android 中常见的文件操作方法,复习 Android 界面编程。
直接进入正题~
基础知识
1.SharedPreferences 的使用
使用SharedPreferences储存用户名和密码,SharedPreferences是直接处理xml文件,不需要做字符串分割,存储效率会比使用内部存储,和外部存储存储用户名和密码高。
(1) SharedPreferences 的读取
在 Android 中,用于获取 SharedPreferences 的接?是 getSharedPreferences(String, int) 函数。 两个参数的意义:
String: Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor.
int: Operating mode. Use 0 or MODE_PRIVATE for the default operation.
我们对 SharedPreferences 的读取操作是通过 getSharedPreferences(String, int) 函数返回的 SharedPreferences 对象的方法来完成的。查阅文档可以看到,SharedPreferences 支持如下几种方法读取之前存储的数据:
-
-
- abstract Map<String, ?> getAll()
- abstract boolean getBoolean(String key, boolean defValue)
- abstract float getFloat(String key, float defValue)
- abstract int getInt(String key, int defValue)
- abstract long getLong(String key, long defValue)
- abstract String getString(String key, String defValue)
- abstract Set<String> getStringSet(String key, Set<String> defValues)
-
所有方法都需要传入一个 defValue 参数,在给定的 key 不存在时,SharedPreferences 会直接返回 这个默认值。
(2)SharedPreferences 的写入
所有对 SharedPreferences 的写入操作,都必须通过 SharedPreferences.edit() 函数返回的 Editor对象来完成。
举例:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences("MY_PREFERENCE", Context.MODE_PRIVATE);
// Alternatively, if you need just one shared preference file for your activity, you can use the getPreferences() method:
// SharedPreferences sharedPref =getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KEY_SCORE", newHighScore);
editor.commit();
使用SharedPreferences将用户名和密码保存在本地后,可以在\data\data\+包名+\shared_prefs目录下找到一个info.xml文件
2.Android 中的文件操作
Android 中的存储空间分为两种:Internal Storage 和 External Storage.
(1)Internal Storage
默认情况下,保存在 Internal Storage 的文件只有应用程序可见,其他应用,以及用户本?是无法访问这些文件的。
向 Internal Storage 写入文件的示例代码如下:
try (FileOutputStream fileOutputStream = openFileOutput(FILE_NAME, MODE_PRIVATE)) {
String str = "Hello, World!";
fileOutputStream.write(str.getBytes());
Log.i("TAG", "Successfully saved file.");
} catch (IOException ex) {
Log.e("TAG", "Fail to save file.");
}
若对应的文件不存在,openFileOutput(String, int) 函数会直接新建文件。注意传入的文件名参数不能含有 path separators(即 '/'). 该函数返回一个 FileOutputStream 对象,可以调用 write() 方法写入内容。
相应地,文件的读取可以使用 openFileInput(String) 来读取文件。该函数返回一个 FileInput- Stream,调用 read() 方法读取内容。
try (FileInputStream fileInputStream =openFileInput(FILE_NAME)) {
byte[] contents = new byte[fileInputStream.available()];
fileInputStream.read(contents);
} catch (IOException ex) {
Log.e("TAG", "Fail to read file.");
}
(2)External Storage
Android 支持使用 Java 的文件 API 来读写文件,但是关键的点在于要有一个合适的路径。如果你要存储一些公开的,体积较大的文件(如媒体文件),External Storage 就是一个比较合适的地方。如文档中所说:
All Android devices have two file storage areas: “internal” and “external” storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable stor- age medium such as a micro SD card (external storage). Some devices divide the permanent storage space into “internal” and “external” partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not.
无论是否支持外置 SD 卡,所有的 Android 设备都会将存储空间分为 internal 和 external 两部分。
要往 External Storage 写入文件,需要在 AndroidManifest.xml 文件中声明权限:
-
-
<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ... </manifest>
-
随后调用 getExternalFilesDir(String type) 或 Environment.getExternalStoragePublicDirectory()来获取 SD 卡路径。两者的区别在于:前者指向的目录会在应用卸载时被删除,而后者不会。
上面的两个函数均返回一个 File 对象,代表一个目录路径,使用这个 File 对象,再结合文件名,即 可创建 FileInputStream 或 FileOutputStream 来进?文件读写。
举例:
-
-
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
-
您可能想查找下面的文章:
- Android开发简单服务器
- android开发使用组件心得
- 1.2 开发环境搭建
- android入门,看这一本书就够了,android入门,
- Android开发笔记(8)——调用子Activity,androidactivity
- Android开发笔记(9)——初步设置Menu,androidmenu
- Android开发笔记(6)——类的设定与继承,android笔记
- Android开发笔记(5)——方法调用(基础),android笔记
- Android开发笔记(4)——MainActivity.java文件修改&布局嵌套,androidmainactivity
- Android开发笔记(2)——ViewGroup,androidviewgroup