赞
踩
数据和程序是应用构成的两个核心要素,数据存储永远是应用开发中最重要的主题之一,也是开发平台必须提供的基础功能。不光是在Android平台上,在其他的平台上,数据的存储永远是不可缺少的一块。Android的数据存储是构建在Linux的文件系统上,它充分利用Linux的账号系统来限定应用对数据的访问,部署了一套安全和灵活并重的数据存储解决方案。Android的文件框架,以及各种数据存储手段,具体包括:Android的文件系统操作,设置文件的使用,数据库的使用,数据源组件的使用以及云端数据的存储。
目录 | 内容 |
system | 系统目录,放置在Android运行所需的核心库 |
data | 应用目录,放置着运行在Android上的应用及其数据 |
sdcar | 扩展存储卡目录,用来存放共享的数据 |
mnt | 记录Android挂载的外部存储信息 |
- // =================get SDCard information===================
- public static boolean isSdcardAvailable() {
- String status = Environment.getExternalStorageState();
- //Environment.MEDIA_MOUNTED表示SD卡正常挂载
- if (status.equals(Environment.MEDIA_MOUNTED)) {
- return true;
- }
- return false;
- }
-
- public static long getSDAllSizeKB() {
- //sd卡的位置
- File path = Environment.getExternalStorageDirectory();
- //StatFs获取的都是以block为单位的
- StatFs sf = new StatFs(path.getPath());
- // 得到单个block的大小
- long blockSize = sf.getBlockSize();
- // 获取所有数据块数
- long allBlocks = sf.getBlockCount();
- // 返回SD卡大小
- return (allBlocks * blockSize) / 1024; // KB
- }
-
- /**
- * free size for normal application
- * @return
- */
- public static long getSDAvalibleSizeKB() {
- File path = Environment.getExternalStorageDirectory();
- StatFs sf = new StatFs(path.getPath());
- long blockSize = sf.getBlockSize();
- long avaliableSize = sf.getAvailableBlocks();
- return (avaliableSize * blockSize) / 1024;// KB
- }
- case R.id.button1: {
- Log.d("TEST", "sdcard?"+FileUtil.isSdcardAvailable());
- Log.d("TEST", "全部容量"+(float)FileUtil.getSDAllSizeKB()/1024/1024);
- Log.d("TEST", "可用容量"+(float)FileUtil.getSDAvalibleSizeKB()/1024/1024);
- Toast.makeText(this, "status", Toast.LENGTH_SHORT).show();
- break;
- }
- /**
- * @param director 文件夹名称
- * @return
- */
- public static boolean isFileExist(String director) {
- File file = new File(Environment.getExternalStorageDirectory()
- + File.separator + director);
- return file.exists();
- }
-
- /**
- * create multiple director
- * @param path
- * @return
- */
- public static boolean createFile(String director) {
- if (isFileExist(director)) {
- return true;
- } else {
- File file = new File(Environment.getExternalStorageDirectory()
- + File.separator + director);
- if (!file.mkdirs()) {
- return false;
- }
- return true;
- }
- }
- case R.id.button2: {
- Log.d("TEST", "example文件夹存在?"+FileUtil.isFileExist("example"));
- Log.d("TEST", "创建forexample文件夹"+FileUtil.createFile("forexample"));
- Toast.makeText(this, "IsFile", Toast.LENGTH_SHORT).show();
- break;
- }
- /**
- *
- * @param director
- * (you don't need to begin with
- * Environment.getExternalStorageDirectory()+File.separator)
- * @param fileName
- * @param content
- * @param encoding
- * (UTF-8...)
- * @param isAppend
- * : Context.MODE_APPEND
- * @return
- */
- public static File writeToSDCardFile(String directory, String fileName,
- String content, String encoding, boolean isAppend) {
- // mobile SD card path +path
- File file = null;
- OutputStream os = null;
- try {
- if (!createFile(directory)) {
- return file;
- }
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- os = new FileOutputStream(file, isAppend);
- if (encoding.equals("")) {
- os.write(content.getBytes());
- } else {
- os.write(content.getBytes(encoding));
- }
- os.flush();
- } catch (IOException e) {
- Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage());
- } finally {
- try {
- if (os != null) {
- os.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return file;
- }
-
- /**
- * write data from inputstream to SDCard
- */
- public File writeToSDCardFromInput(String directory, String fileName,
- InputStream input) {
- File file = null;
- OutputStream os = null;
- try {
- if (createFile(directory)) {
- return file;
- }
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- os = new FileOutputStream(file);
- byte[] data = new byte[bufferd];
- int length = -1;
- while ((length = input.read(data)) != -1) {
- os.write(data, 0, length);
- }
- // clear cache
- os.flush();
- } catch (Exception e) {
- Log.e("FileUtil", "" + e.getMessage());
- e.printStackTrace();
- } finally {
- try {
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return file;
- }
从上面可以看到有两种写入的方法,一种是将字符串直接写入,另一种是将数据流写到文件中。还有一点要提的是file的默认目录就是sdcard的目录,所以开头不必每次都要加sdcard的目录路径。
FileOutputStream(file, isAppend) 两个参数,左边是File文件,而右边是一个boolean值,为true时,数据将会接在原来文件的后面写入,而false是则会覆盖。 读:
- public static String ReadFromSDCardFile(String directory,String fileName){
- String res="";
- File file = null;
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- try {
- FileInputStream fis = new FileInputStream(file);
- int length = fis.available();
- byte [] buffer = new byte[length];
- fis.read(buffer); //将字节按照编码格式转成字符串
- res = EncodingUtils.getString(buffer, "UTF-8");
- fis.close();
- return res;
- }catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- Log.d("TEST", "FileNotFound");
- e.printStackTrace();
- }catch (Exception e) {
- Log.d("TEST", "Can Not Open File");
- e.printStackTrace();
- }
- return null;
- }
- case R.id.button3: {
- FileUtil.writeToSDCardFile("forexample", "test.txt",
- editText.getText().toString(), "UTF-8", true);
- Toast.makeText(this, "WriteFile", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button4: {
- textView.setText(FileUtil.ReadFromSDCardFile("forexample", "test.txt"));
- Toast.makeText(this, "ReadFile", Toast.LENGTH_SHORT).show();
- break;
- }
(2)放在该应用数据目录下的文件读写
存储在应用目录下的私有数据目录,通常不会通过File类的方式直接读写,而是利用一些封装过的类或函数来操作。一般可以通过Context.openFileOutput来执行。
在Activity加入两个方法,分别为文件的读和写
- public void writeFile(String fileName,String writestr){
- try{
- FileOutputStream fout =openFileOutput(fileName,MODE_PRIVATE);
- byte [] bytes = writestr.getBytes();
- fout.write(bytes);
- fout.close();
- }
- catch(Exception e){
- e.printStackTrace();
- }
- }
-
- //读数据
- public String readFile(String fileName){
- String res="";
- try{
- FileInputStream fin = openFileInput(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;
- }
- case R.id.button5: {
- writeFile("test2.txt",editText.getText().toString());
- Toast.makeText(this, "WritePrivateFile", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button6: {
- textView.setText(readFile("test2.txt"));
- Toast.makeText(this, "ReadPrivateFile", Toast.LENGTH_SHORT).show();
- break;
- }
最后不要忘记在配置文件中声明权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
用户在使用应用时,常常会有一些个人偏好。为了满足不同用户的需求,应用通常会提供对应的设置项(Preference),让用户根据自己的喜好选择。这些设置信息会存储在本地并进行结构化地展示,使用户可以编辑。
- //在界面组件或服务组件中调用,构造应用默认的设置文件,默认文件名字为_preferences.xml
- //userInfo = PreferenceManager.getDefaultSharedPreferences(this);
- //或获取指定名字的SharedPreferences对象 参数分别为存储的文件名和存储模式。
- userInfo = getSharedPreferences("preferences", Activity.MODE_PRIVATE);
-
- //读取数据,如果无法找到则会使用默认值
- String username = userInfo.getString("name", "未定义姓名");
- String msg = userInfo.getString("msg", "未定义信息");
- //显示文本
- textView.setText(username+","+msg);
- case R.id.button7: {
- //获得SharedPreferences的编辑器
- SharedPreferences.Editor editor = userInfo.edit();
- //将信息存入相应的键值中
- editor.putString("name", editText.getText().toString()).commit();
- Toast.makeText(this, "SetName", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button8: {
- //获得SharedPreferences的编辑器
- SharedPreferences.Editor editor = userInfo.edit();
- //将信息存入相应的键值中ss
- editor.putString("msg", editText.getText().toString()).commit();
- Toast.makeText(this, "SetMessage", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button9: { //获得SharedPreferences文件
- userInfo = getSharedPreferences("preferences", Activity.MODE_PRIVATE);
- String username = userInfo.getString("name", "未定义姓名");
- String msg = userInfo.getString("msg", "未定义信息");
- textView.setText(username+","+msg);
- Toast.makeText(this, "ShowMsg", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button10: { //输出XML文件
- textView.setText(print());
- Toast.makeText(this, "ShowXML", Toast.LENGTH_SHORT).show();
- break;
- }
- package com.example.administrator.myapplication;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import android.os.Environment;
- import android.os.StatFs;
- import android.util.Log;
-
- import org.apache.http.util.EncodingUtils;
-
- public class FileUtil {
- private static int bufferd = 1024;
- private FileUtil() {
- }
-
- /*
- * <!-- 在SDCard中创建与删除文件权限 --> <uses-permission
- * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!--
- * 往SDCard写入数据权限 --> <uses-permission
- * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- */
- // =================get SDCard information===================
- public static boolean isSdcardAvailable() {
- String status = Environment.getExternalStorageState();
- if (status.equals(Environment.MEDIA_MOUNTED)) {
- return true;
- }
- return false;
- }
-
- public static long getSDAllSizeKB() {
- // get path of sdcard
- File path = Environment.getExternalStorageDirectory();
- //StatFs获取的都是以block为单位的 http://blog.csdn.net/pang3510726681/article/details/6969557
- StatFs sf = new StatFs(path.getPath());
- // get single block size(Byte)
- long blockSize = sf.getBlockSize();
- // 获取所有数据块数
- long allBlocks = sf.getBlockCount();
- // 返回SD卡大小
- return (allBlocks * blockSize) / 1024; // KB
- }
-
- /**
- * free size for normal application
- *
- * @return
- */
- public static long getSDAvalibleSizeKB() {
- File path = Environment.getExternalStorageDirectory();
- StatFs sf = new StatFs(path.getPath());
- long blockSize = sf.getBlockSize();
- long avaliableSize = sf.getAvailableBlocks();
- return (avaliableSize * blockSize) / 1024;// KB
- }
-
- // =====================File Operation==========================
- /**
- * @param director 文件夹名称
- * @return
- */
- public static boolean isFileExist(String director) {
- File file = new File(Environment.getExternalStorageDirectory()
- + File.separator + director);
- return file.exists();
- }
-
-
- public static boolean createFile(String director) {
- if (isFileExist(director)) {
- return true;
- } else {
- File file = new File(Environment.getExternalStorageDirectory()
- + File.separator + director);
- if (!file.mkdirs()) {
- return false;
- }
- return true;
- }
- }
-
- public static File writeToSDCardFile(String directory, String fileName,
- String content, boolean isAppend) {
- return writeToSDCardFile(directory, fileName, content, "", isAppend);
- }
-
-
- public static File writeToSDCardFile(String directory, String fileName,
- String content, String encoding, boolean isAppend) {
- // mobile SD card path +path
- File file = null;
- OutputStream os = null;
- try {
- if (!createFile(directory)) {
- return file;
- }
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- os = new FileOutputStream(file, isAppend);
- if (encoding.equals("")) {
- os.write(content.getBytes());
- } else {
- os.write(content.getBytes(encoding));
- }
- os.flush();
- } catch (IOException e) {
- Log.e("FileUtil", "writeToSDCardFile:" + e.getMessage());
- } finally {
- try {
- if (os != null) {
- os.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return file;
- }
-
- /**
- * write data from inputstream to SDCard
- */
- public static File writeToSDCardFromInput(String directory, String fileName,
- InputStream input) {
- File file = null;
- OutputStream os = null;
- try {
- if (createFile(directory)) {
- return file;
- }
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- os = new FileOutputStream(file);
- byte[] data = new byte[bufferd];
- int length = -1;
- while ((length = input.read(data)) != -1) {
- os.write(data, 0, length);
- }
- // clear cache
- os.flush();
- } catch (Exception e) {
- Log.e("FileUtil", "" + e.getMessage());
- e.printStackTrace();
- } finally {
- try {
- os.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return file;
- }
-
- public static String ReadFromSDCardFile(String directory,String fileName){
- String res="";
- File file = null;
- file = new File(Environment.getExternalStorageDirectory()
- + File.separator + directory + File.separator + fileName);
- try {
- FileInputStream fis = new FileInputStream(file);
- int length = fis.available();
- byte [] buffer = new byte[length];
- fis.read(buffer);
- res = EncodingUtils.getString(buffer,"UTF-8");
- fis.close();
- return res;
- }catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- Log.d("TEST", "FileNotFound");
- e.printStackTrace();
- }catch (Exception e) {
- Log.d("TEST", "Can Not Open File");
- e.printStackTrace();
- }
- return null;
- }
- }
MainActivity
- package com.example.administrator.myapplication;
- import android.app.Activity;
- import android.content.SharedPreferences;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
-
- import org.apache.http.util.EncodingUtils;
-
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStreamReader;
-
- public class MainActivity extends Activity implements View.OnClickListener {
- /**
- * 存储后的文件路径:/data/data/<package name>/shares_prefs + 文件名.xml
- */
- public static final String PATH = "/data/data/com.example.administrator/shared_prefs/preferences.xml";
- private SharedPreferences userInfo;
- private Button button1;
- private Button button2;
- private Button button3;
- private Button button4;
- private Button button5;
- private Button button6;
- private Button button7;
- private Button button8;
- private Button button9;
- private Button button10;
- private TextView textView;
- private EditText editText;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- // 获得界面的控件
- textView = (TextView) findViewById(R.id.textView1);
- editText = (EditText) findViewById(R.id.editText1);
- button1 = (Button) findViewById(R.id.button1);
- button1.setOnClickListener(this);
- button2 = (Button) findViewById(R.id.button2);
- button2.setOnClickListener(this);
- button3 = (Button) findViewById(R.id.button3);
- button3.setOnClickListener(this);
- button4 = (Button) findViewById(R.id.button4);
- button4.setOnClickListener(this);
- button5 = (Button) findViewById(R.id.button5);
- button5.setOnClickListener(this);
- button6 = (Button) findViewById(R.id.button6);
- button6.setOnClickListener(this);
- button7 = (Button) findViewById(R.id.button7);
- button7.setOnClickListener(this);
- button8 = (Button) findViewById(R.id.button8);
- button8.setOnClickListener(this);
- button9 = (Button) findViewById(R.id.button9);
- button9.setOnClickListener(this);
- button10 = (Button) findViewById(R.id.button10);
- button10.setOnClickListener(this);
- //在界面组件或服务组件中调用,构造应用默认的设置文件,默认文件名字为_preferences.xml
- //userInfo = PreferenceManager.getDefaultSharedPreferences(this);
- //或获取指定名字的SharedPreferences对象 参数分别为存储的文件名和存储模式。
- userInfo = getSharedPreferences("preferences.xml", Activity.MODE_PRIVATE);
- //读取数据,如果无法找到则会使用默认值
- String username = userInfo.getString("name", "未定义姓名");
- String msg = userInfo.getString("msg", "未定义信息");
- //显示文本
- textView.setText(username + "," + msg);
- }
-
- public void onClick(View v) {
- // TODO Auto-generated method stub
- switch (v.getId()) {
- case R.id.button1: {
- Log.d("TEST", "sdcard?" + FileUtil.isSdcardAvailable());
- Log.d("TEST", "全部容量" + (float) FileUtil.getSDAllSizeKB() / 1024 / 1024);
- Log.d("TEST", "可用容量" + (float) FileUtil.getSDAvalibleSizeKB() / 1024 / 1024);
- Toast.makeText(this,"全部容量" + (float) FileUtil.getSDAllSizeKB() / 1024 / 1024, Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button2: {
- Log.d("TEST", "example文件夹存在?" + FileUtil.isFileExist("example"));
- Log.d("TEST", "创建forexample文件夹" + FileUtil.createFile("forexample"));
- Toast.makeText(this,""+ FileUtil.isFileExist("forexample"), Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button3: {
- FileUtil.writeToSDCardFile("forexample", "test.txt",
- editText.getText().toString(), "UTF-8", true);
- Toast.makeText(this, "WriteFile", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button4: {
- textView.setText(FileUtil.ReadFromSDCardFile("forexample", "test.txt"));
- Toast.makeText(this, "ReadFile", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button5: {
- writeFile("test2.txt", editText.getText().toString());
- Toast.makeText(this, "WritePrivateFile", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button6: {
- textView.setText(readFile("test2.txt"));
- Toast.makeText(this, "ReadPrivateFile", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button7: {
- //获得SharedPreferences的编辑器
- SharedPreferences.Editor editor = userInfo.edit();
- //将信息存入相应的键值中
- editor.putString("name", editText.getText().toString()).commit();
- Toast.makeText(this, "SetName", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button8: {
- //获得SharedPreferences的编辑器
- SharedPreferences.Editor editor = userInfo.edit();
- //将信息存入相应的键值中ss
- editor.putString("msg", editText.getText().toString()).commit();
- Toast.makeText(this, "SetMessage", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button9: {
- userInfo = getSharedPreferences("preferences.xml", Activity.MODE_PRIVATE);
- String username = userInfo.getString("name", "未定义姓名");
- String msg = userInfo.getString("msg", "未定义信息");
- textView.setText(username + "," + msg);
- Toast.makeText(this, "ShowMsg", Toast.LENGTH_SHORT).show();
- break;
- }
- case R.id.button10: {
- textView.setText(print());
- Toast.makeText(this, "ShowXML", Toast.LENGTH_SHORT).show();
- break;
- }
- }
- }
-
- public void writeFile(String fileName, String writestr) {
- try {
- FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
- byte[] bytes = writestr.getBytes();
- fout.write(bytes);
- fout.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- //读数据
- public String readFile(String fileName) {
- String res = "";
- try {
- FileInputStream fin = openFileInput(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;
- }
-
- private String print() {
- StringBuffer buff = new StringBuffer();
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- new FileInputStream(PATH)));
- String str;
- while ((str = reader.readLine()) != null) {
- buff.append(str + "/n");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return buff.toString();
- }
- }
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/editText1"
- />
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/textView1"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Status"
- android:id="@+id/button1"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="IsFile"
- android:id="@+id/button2"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="WriteFile"
- android:id="@+id/button3"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="ReadFile"
- android:id="@+id/button4"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="WritePrivateFile"
- android:id="@+id/button5"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="ReadPrivateFile"
- android:id="@+id/button6"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="SetName"
- android:id="@+id/button7"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="SetMessage"
- android:id="@+id/button8"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="ShowMessage"
- android:id="@+id/button9"
- />
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="ShowXML"
- android:id="@+id/button10"
- />
- </LinearLayout>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。