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 plain copy
  1. /**
  2. *MainActivity
  3. *
  4. *@authorzuolongsnail
  5. *
  6. */
  7. publicclassMainActivityextendsActivity{
  8. privateEditTextwriteET;
  9. privateButtonwriteBtn;
  10. privateTextViewcontentView;
  11. publicstaticfinalStringFILENAME="setting.set";
  12. @Override
  13. publicvoidonCreate(BundlesavedInstanceState){
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.main);
  16. writeET=(EditText)findViewById(R.id.write_et);
  17. writeBtn=(Button)findViewById(R.id.write_btn);
  18. contentView=(TextView)findViewById(R.id.contentview);
  19. writeBtn.setOnClickListener(newOperateOnClickListener());
  20. }
  21. classOperateOnClickListenerimplementsOnClickListener{
  22. @Override
  23. publicvoidonClick(Viewv){
  24. writeFiles(writeET.getText().toString());
  25. contentView.setText(readFiles());
  26. System.out.println(getFilesDir());
  27. }
  28. }
  29. //保存文件内容
  30. privatevoidwriteFiles(Stringcontent){
  31. try{
  32. //打开文件获取输出流,文件不存在则自动创建
  33. FileOutputStreamfos=openFileOutput(FILENAME,
  34. Context.MODE_PRIVATE);
  35. fos.write(content.getBytes());
  36. fos.close();
  37. }catch(Exceptione){
  38. e.printStackTrace();
  39. }
  40. }
  41. //读取文件内容
  42. privateStringreadFiles(){
  43. Stringcontent=null;
  44. try{
  45. FileInputStreamfis=openFileInput(FILENAME);
  46. ByteArrayOutputStreambaos=newByteArrayOutputStream();
  47. byte[]buffer=newbyte[1024];
  48. intlen=0;
  49. while((len=fis.read(buffer))!=-1){
  50. baos.write(buffer,0,len);
  51. }
  52. content=baos.toString();
  53. fis.close();
  54. baos.close();
  55. }catch(Exceptione){
  56. e.printStackTrace();
  57. }
  58. returncontent;
  59. }
  60. }

程序截图:

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

[java] view plain copy
  1. /**
  2. *文件存储数据方式工具类
  3. *
  4. *@authorzuolongsnail
  5. */
  6. publicclassFilesUtil{
  7. /**
  8. *保存文件内容
  9. *
  10. *@paramc
  11. *@paramfileName
  12. *文件名称
  13. *@paramcontent
  14. *内容
  15. */
  16. privatevoidwriteFiles(Contextc,StringfileName,Stringcontent,intmode)
  17. throwsException{
  18. //打开文件获取输出流,文件不存在则自动创建
  19. FileOutputStreamfos=c.openFileOutput(fileName,mode);
  20. fos.write(content.getBytes());
  21. fos.close();
  22. }
  23. /**
  24. *读取文件内容
  25. *
  26. *@paramc
  27. *@paramfileName
  28. *文件名称
  29. *@return返回文件内容
  30. */
  31. privateStringreadFiles(Contextc,StringfileName)throwsException{
  32. ByteArrayOutputStreambaos=newByteArrayOutputStream();
  33. FileInputStreamfis=c.openFileInput(fileName);
  34. byte[]buffer=newbyte[1024];
  35. intlen=0;
  36. while((len=fis.read(buffer))!=-1){
  37. baos.write(buffer,0,len);
  38. }
  39. Stringcontent=baos.toString();
  40. fis.close();
  41. baos.close();
  42. returncontent;
  43. }
  44. }

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

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

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

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

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

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

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

[java] view plain copy
  1. /**
  2. *MainActivity
  3. *
  4. *@authorzuolongsnail
  5. */
  6. publicclassMainActivityextendsActivity{
  7. privateEditTextkeyET;
  8. privateEditTextvalueET;
  9. privateButtoninsertBtn;
  10. privateButtondeleteBtn;
  11. privateButtonmodifyBtn;
  12. privateButtonqueryBtn;
  13. privateButtonclearBtn;
  14. privateTextViewtextView;
  15. /**存储的文件名*/
  16. publicstaticfinalStringDATABASE="Database";
  17. /**存储后的文件路径:/data/data/<packagename>/shares_prefs+文件名.xml*/
  18. publicstaticfinalStringPATH="/data/data/code.sharedpreferences/shared_prefs/Database.xml";
  19. @Override
  20. publicvoidonCreate(BundlesavedInstanceState){
  21. super.onCreate(savedInstanceState);
  22. setContentView(R.layout.main);
  23. keyET=(EditText)findViewById(R.id.key);
  24. valueET=(EditText)findViewById(R.id.value);
  25. insertBtn=(Button)findViewById(R.id.insert);
  26. deleteBtn=(Button)findViewById(R.id.delete);
  27. modifyBtn=(Button)findViewById(R.id.modify);
  28. queryBtn=(Button)findViewById(R.id.query);
  29. clearBtn=(Button)findViewById(R.id.clear);
  30. //用于显示存储文件中数据
  31. textView=(TextView)findViewById(R.id.content);
  32. insertBtn.setOnClickListener(newOperateOnClickListener());
  33. deleteBtn.setOnClickListener(newOperateOnClickListener());
  34. modifyBtn.setOnClickListener(newOperateOnClickListener());
  35. queryBtn.setOnClickListener(newOperateOnClickListener());
  36. clearBtn.setOnClickListener(newOperateOnClickListener());
  37. }
  38. classOperateOnClickListenerimplementsOnClickListener{
  39. @Override
  40. publicvoidonClick(Viewv){
  41. //获取SharedPreferences对象
  42. SharedPreferencessp=getSharedPreferences(DATABASE,
  43. Activity.MODE_PRIVATE);
  44. //获取Editor对象
  45. Editoreditor=sp.edit();
  46. // 获取界面中的信息
  47. Stringkey=keyET.getText().toString();
  48. Stringvalue=valueET.getText().toString();
  49. switch(v.getId()){
  50. //插入数据
  51. caseR.id.insert:
  52. editor.putString(key,value);
  53. editor.commit();
  54. textView.setText(MainActivity.this.print());
  55. break;
  56. //删除数据
  57. caseR.id.delete:
  58. editor.remove(key);
  59. editor.commit();
  60. textView.setText(MainActivity.this.print());
  61. break;
  62. //修改数据
  63. caseR.id.modify:
  64. editor.putString(key,value);
  65. editor.commit();
  66. textView.setText(MainActivity.this.print());
  67. break;
  68. //查询数据
  69. caseR.id.query:
  70. Stringresult=sp.getString(key,"");
  71. textView.setText("key="+key+",value="+result);
  72. break;
  73. //清空所有数据
  74. caseR.id.clear:
  75. editor.clear();
  76. editor.commit();
  77. textView.setText(MainActivity.this.print());
  78. break;
  79. }
  80. }
  81. }
  82. /**获取存储文件的数据*/
  83. privateStringprint(){
  84. StringBufferbuff=newStringBuffer();
  85. try{
  86. BufferedReaderreader=newBufferedReader(newInputStreamReader(
  87. newFileInputStream(PATH)));
  88. Stringstr;
  89. while((str=reader.readLine())!=null){
  90. buff.append(str+"/n");
  91. }
  92. }catch(Exceptione){
  93. e.printStackTrace();
  94. }
  95. returnbuff.toString();
  96. }
  97. }

程序截图:

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

[java] view plain copy
  1. /**
  2. *SharedPreferences存储数据方式工具类
  3. *@authorzuolongsnail
  4. */
  5. publicclassSharedPrefsUtil{
  6. publicfinalstaticStringSETTING="Setting";
  7. publicstaticvoidputValue(Contextcontext,Stringkey,intvalue){
  8. Editorsp=context.getSharedPreferences(SETTING,Context.MODE_PRIVATE).edit();
  9. sp.putInt(key,value);
  10. sp.commit();
  11. }
  12. publicstaticvoidputValue(Contextcontext,Stringkey,booleanvalue){
  13. Editorsp=context.getSharedPreferences(SETTING,Context.MODE_PRIVATE).edit();
  14. sp.putBoolean(key,value);
  15. sp.commit();
  16. }
  17. publicstaticvoidputValue(Contextcontext,Stringkey,Stringvalue){
  18. Editorsp=context.getSharedPreferences(SETTING,Context.MODE_PRIVATE).edit();
  19. sp.putString(key,value);
  20. sp.commit();
  21. }
  22. publicstaticintgetValue(Contextcontext,Stringkey,intdefValue){
  23. SharedPreferencessp=context.getSharedPreferences(SETTING,Context.MODE_PRIVATE);
  24. intvalue=sp.getInt(key,defValue);
  25. returnvalue;
  26. }
  27. publicstaticbooleangetValue(Contextcontext,Stringkey,booleandefValue){
  28. SharedPreferencessp=context.getSharedPreferences(SETTING,Context.MODE_PRIVATE);
  29. booleanvalue=sp.getBoolean(key,defValue);
  30. returnvalue;
  31. }
  32. publicstaticStringgetValue(Contextcontext,Stringkey,StringdefValue){
  33. SharedPreferencessp=context.getSharedPreferences(SETTING,Context.MODE_PRIVATE);
  34. Stringvalue=sp.getString(key,defValue);
  35. returnvalue;
  36. }
  37. }




更多相关文章

  1. Android安装常见的一些解决方法
  2. android 关机闹钟
  3. Android(安卓)简单的Http框架
  4. Android(安卓)Resources Overview —— Android(安卓)资源文件
  5. Android——“i分享”APP开发Day11
  6. 【Android测试工具】02. Android抓包解析全过程
  7. Android:自定义DialogFragment的内容和按钮
  8. android 访问/assets 和/res目录下文件的方法
  9. Android写SD卡的坑

随机推荐

  1. Android退出程序的多种方法
  2. 键盘自动弹出解决
  3. PackageManagerService简介
  4. android 开发中常用颜色,以及一些颜色的代
  5. android appwidget service的初始化
  6. Android保留两位小数方法
  7. 自定义自己的AlertDialog
  8. App应用之提交到各大市场渠道
  9. Android(安卓)bluetooth介绍(三): 蓝牙扫描(
  10. Android5.0通知变化浅析