Android基本数据存储方法

来源:互联网 发布:地图标注软件 编辑:程序博客网 时间:2024/05/19 04:54

1.文件存储数据使用了Java中的IO操作来进行文件的保存和读取,只不过Android在Context类中封装好了输入流和输出流的获取方法。
创建的存储文件保存在/data/data/<package name>/files文件夹下。

 

 

2.操作。
保存文件内容:通过Context.openFileOutput获取输出流,参数分别为文件名和存储模式。
读取文件内容:通过Context.openFileInput获取输入流,参数为文件名。
删除文件:Context.deleteFile删除指定的文件,参数为将要删除的文件的名称。
获取文件名列表:通过Context.fileList获取files目录下的所有文件名数组。
*获取文件路径的方法:
绝对路径:/data/data/<package name>/files/filename
Context:Context.getFilesDir()可以获取到"/data/data/<package name>/files"

 

3.四种文件保存的模式。
Context.MODE_PRIVATE 为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下写入的内容会覆盖原文件的内容。
Context.MODE_APPEND 检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_WORLD_READABLE 表示当前文件可以被其他应用读取。
MODE_WORLD_WRITEABLE 表示当前文件可以被其他应用写入。
在使用模式时,可以用"+"来选择多种模式,比如openFileOutput(FILENAME, Context.MODE_PRIVATE + MODE_WORLD_READABLE);

 

下面通过程序来演示下文件存储的使用。完整代码下载:android_files.rar

[java] view plaincopy
  1. /** 
  2.  * MainActivity 
  3.  *  
  4.  * @author zuolongsnail 
  5.  *  
  6.  */  
  7. public class MainActivity extends Activity {  
  8.     private EditText writeET;  
  9.     private Button writeBtn;  
  10.     private TextView contentView;  
  11.     public static final String FILENAME = "setting.set";  
  12.   
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.main);  
  17.         writeET = (EditText) findViewById(R.id.write_et);  
  18.         writeBtn = (Button) findViewById(R.id.write_btn);  
  19.         contentView = (TextView) findViewById(R.id.contentview);  
  20.         writeBtn.setOnClickListener(new OperateOnClickListener());  
  21.     }  
  22.   
  23.     class OperateOnClickListener implements OnClickListener {  
  24.         @Override  
  25.         public void onClick(View v) {  
  26.             writeFiles(writeET.getText().toString());  
  27.             contentView.setText(readFiles());  
  28.             System.out.println(getFilesDir());  
  29.         }  
  30.     }  
  31.   
  32.     // 保存文件内容  
  33.     private void writeFiles(String content) {  
  34.         try {  
  35.             // 打开文件获取输出流,文件不存在则自动创建  
  36.             FileOutputStream fos = openFileOutput(FILENAME,  
  37.                     Context.MODE_PRIVATE);  
  38.             fos.write(content.getBytes());  
  39.             fos.close();  
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.   
  45.     // 读取文件内容  
  46.     private String readFiles() {  
  47.         String content = null;  
  48.         try {  
  49.             FileInputStream fis = openFileInput(FILENAME);  
  50.             ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  51.             byte[] buffer = new byte[1024];  
  52.             int len = 0;  
  53.             while ((len = fis.read(buffer)) != -1) {  
  54.                 baos.write(buffer, 0, len);  
  55.             }  
  56.             content = baos.toString();  
  57.             fis.close();  
  58.             baos.close();  
  59.         } catch (Exception e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.         return content;  
  63.     }  
  64. }  

程序截图:

 

提供一个文件存储数据的工具类:

[java] view plaincopy
  1. /** 
  2.  * 文件存储数据方式工具类 
  3.  *  
  4.  * @author zuolongsnail 
  5.  */  
  6. public class FilesUtil {  
  7.     /** 
  8.      * 保存文件内容 
  9.      *  
  10.      * @param c 
  11.      * @param fileName 
  12.      *            文件名称 
  13.      * @param content 
  14.      *            内容 
  15.      */  
  16.     private void writeFiles(Context c, String fileName, String content, int mode)  
  17.             throws Exception {  
  18.         // 打开文件获取输出流,文件不存在则自动创建  
  19.         FileOutputStream fos = c.openFileOutput(fileName, mode);  
  20.         fos.write(content.getBytes());  
  21.         fos.close();  
  22.     }  
  23.   
  24.     /** 
  25.      * 读取文件内容 
  26.      *  
  27.      * @param c 
  28.      * @param fileName 
  29.      *            文件名称 
  30.      * @return 返回文件内容 
  31.      */  
  32.     private String readFiles(Context c, String fileName) throws Exception {  
  33.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  34.         FileInputStream fis = c.openFileInput(fileName);  
  35.         byte[] buffer = new byte[1024];  
  36.         int len = 0;  
  37.         while ((len = fis.read(buffer)) != -1) {  
  38.             baos.write(buffer, 0, len);  
  39.         }  
  40.         String content = baos.toString();  
  41.         fis.close();  
  42.         baos.close();  
  43.         return content;  
  44.     }  
  45. }  

1.概述。SharePreferences是用来存储一些简单配置信息的一种机制,使用Map数据结构来存储数据,以键值对的方式存储,采用了XML格式将数据存储到设备中。例如保存登录用户的用户名和密码。只能在同一个包内使用,不能在不同的包之间使用,其实也就是说只能在创建它的应用中使用,其他应用无法使用。

创建的存储文件保存在/data/data/<package name>/shares_prefs文件夹下。

 

 

2.使用。
通过Context.getSharedPreferences方法获取SharedPreferences对象,参数分别为存储的文件名和存储模式。

[java] view plaincopy
  1. // 获取SharedPreferences对象  
  2. SharedPreferences sp = getSharedPreferences(DATABASE, Activity.MODE_PRIVATE);  
  3. // 获取Editor对象  
  4. Editor editor = sp.edit();  

 

3.操作。SharePreferences存储数据是通过获取Editor编辑器对象来操作的。
插入数据:
调用Editor.putxxxx方法,两个参数分别为键和值。
获取数据:
调用Editor.getxxxx方法,两个参数分别为键和不存在指定键时的默认值。
删除数据:
调用Editor.remove方法,参数为指定的键。
清空所有数据:
调用Editor.clear方法
上述所有方法调用都要执行Editor.commit方法来提交。

 

下面通过对数据的增删改查来演示下SharePreferences的使用。

完整程序下载地址:android_sharedpreferences.rar

[java] view plaincopy
  1. /** 
  2.  * MainActivity 
  3.  *  
  4.  * @author zuolongsnail 
  5.  */  
  6. public class MainActivity extends Activity {  
  7.     private EditText keyET;  
  8.     private EditText valueET;  
  9.     private Button insertBtn;  
  10.     private Button deleteBtn;  
  11.     private Button modifyBtn;  
  12.     private Button queryBtn;  
  13.     private Button clearBtn;  
  14.     private TextView textView;  
  15.     /** 存储的文件名 */  
  16.     public static final String DATABASE = "Database";  
  17.     /** 存储后的文件路径:/data/data/<package name>/shares_prefs + 文件名.xml */  
  18.     public static final String PATH = "/data/data/code.sharedpreferences/shared_prefs/Database.xml";  
  19.   
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.         keyET = (EditText) findViewById(R.id.key);  
  25.         valueET = (EditText) findViewById(R.id.value);  
  26.         insertBtn = (Button) findViewById(R.id.insert);  
  27.         deleteBtn = (Button) findViewById(R.id.delete);  
  28.         modifyBtn = (Button) findViewById(R.id.modify);  
  29.         queryBtn = (Button) findViewById(R.id.query);  
  30.         clearBtn = (Button) findViewById(R.id.clear);  
  31.         // 用于显示存储文件中数据  
  32.         textView = (TextView) findViewById(R.id.content);  
  33.         insertBtn.setOnClickListener(new OperateOnClickListener());  
  34.         deleteBtn.setOnClickListener(new OperateOnClickListener());  
  35.         modifyBtn.setOnClickListener(new OperateOnClickListener());  
  36.         queryBtn.setOnClickListener(new OperateOnClickListener());  
  37.         clearBtn.setOnClickListener(new OperateOnClickListener());  
  38.     }  
  39.   
  40.     class OperateOnClickListener implements OnClickListener {  
  41.         @Override  
  42.         public void onClick(View v) {  
  43.             // 获取SharedPreferences对象  
  44.             SharedPreferences sp = getSharedPreferences(DATABASE,  
  45.                     Activity.MODE_PRIVATE);  
  46.             // 获取Editor对象  
  47.             Editor editor = sp.edit();  
  48.             //  获取界面中的信息  
  49.             String key = keyET.getText().toString();  
  50.             String value = valueET.getText().toString();  
  51.             switch (v.getId()) {  
  52.             // 插入数据  
  53.             case R.id.insert:  
  54.                 editor.putString(key, value);  
  55.                 editor.commit();  
  56.                 textView.setText(MainActivity.this.print());  
  57.                 break;  
  58.             // 删除数据  
  59.             case R.id.delete:  
  60.                 editor.remove(key);  
  61.                 editor.commit();  
  62.                 textView.setText(MainActivity.this.print());  
  63.                 break;  
  64.             // 修改数据  
  65.             case R.id.modify:  
  66.                 editor.putString(key, value);  
  67.                 editor.commit();  
  68.                 textView.setText(MainActivity.this.print());  
  69.                 break;  
  70.             // 查询数据  
  71.             case R.id.query:  
  72.                 String result = sp.getString(key, "");  
  73.                 textView.setText("key=" + key + ",value=" + result);  
  74.                 break;  
  75.             // 清空所有数据  
  76.             case R.id.clear:  
  77.                 editor.clear();  
  78.                 editor.commit();  
  79.                 textView.setText(MainActivity.this.print());  
  80.                 break;  
  81.             }  
  82.   
  83.         }  
  84.     }  
  85.   
  86.     /** 获取存储文件的数据 */  
  87.     private String print() {  
  88.         StringBuffer buff = new StringBuffer();  
  89.         try {  
  90.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
  91.                     new FileInputStream(PATH)));  
  92.             String str;  
  93.             while ((str = reader.readLine()) != null) {  
  94.                 buff.append(str + "/n");  
  95.             }  
  96.         } catch (Exception e) {  
  97.             e.printStackTrace();  
  98.         }  
  99.         return buff.toString();  
  100.     }  
  101. }  

程序截图: 

下面提供一个SharedPreferences工具类,在开发中直接调用即可。

[java] view plaincopy
  1. /** 
  2.  * SharedPreferences存储数据方式工具类 
  3.  * @author zuolongsnail 
  4.  */  
  5. public class SharedPrefsUtil {  
  6.     public final static String SETTING = "Setting";  
  7.     public static void putValue(Context context,String key, int value) {  
  8.          Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();  
  9.          sp.putInt(key, value);  
  10.          sp.commit();  
  11.     }  
  12.     public static void putValue(Context context,String key, boolean value) {  
  13.          Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();  
  14.          sp.putBoolean(key, value);  
  15.          sp.commit();  
  16.     }  
  17.     public static void putValue(Context context,String key, String value) {  
  18.          Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();  
  19.          sp.putString(key, value);  
  20.          sp.commit();  
  21.     }  
  22.     public static int getValue(Context context,String key, int defValue) {  
  23.         SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);  
  24.         int value = sp.getInt(key, defValue);  
  25.         return value;  
  26.     }  
  27.     public static boolean getValue(Context context,String key, boolean defValue) {  
  28.         SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);  
  29.         boolean value = sp.getBoolean(key, defValue);  
  30.         return value;  
  31.     }  
  32.     public static String getValue(Context context,String key, String defValue) {  
  33.         SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);  
  34.         String value = sp.getString(key, defValue);  
  35.         return value;  
  36.     }  
  37. }  




原创粉丝点击