歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> [Android SQLite]數據存儲與訪問 - 內部存儲

[Android SQLite]數據存儲與訪問 - 內部存儲

日期:2017/3/1 10:45:40   编辑:Linux編程

Android系統允許應用程序創建僅能夠自身訪問的私有文件,文件保存在設備的內部存儲器上,在Linux系統下的/data/data/<package name>/files目錄中



系統讀取保存的文件



下面來演示程序

  1. public class Android_DBActivity extends Activity implements OnClickListener
  2. {
  3. private final String FILE_NAME = "fileDemo.txt";
  4. private TextView labelView;
  5. private TextView displayView;
  6. private CheckBox appendBox ;
  7. private EditText entryText;
  8. @Override
  9. public void onCreate(Bundle savedInstanceState)
  10. {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.main);
  13. setupViews();
  14. }
  15. private void setupViews()
  16. {
  17. labelView = (TextView) findViewById(R.id.label);
  18. displayView = (TextView) findViewById(R.id.display);
  19. appendBox = (CheckBox) findViewById(R.id.append);
  20. entryText = (EditText) findViewById(R.id.entry);
  21. findViewById(R.id.write).setOnClickListener(this);
  22. findViewById(R.id.read).setOnClickListener(this);
  23. entryText.selectAll();
  24. entryText.findFocus();
  25. }
  26. @Override
  27. public void onClick(View v)
  28. {
  29. switch (v.getId())
  30. {
  31. case R.id.write:
  32. FileOutputStream fos = null;
  33. try
  34. {
  35. if (appendBox.isChecked())
  36. {
  37. fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
  38. }else
  39. {
  40. fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
  41. }
  42. String text = entryText.getText().toString();
  43. fos.write(text.getBytes());
  44. labelView.setText(String.format("文件寫入成功,寫入長度:%d", text.length()));
  45. } catch (FileNotFoundException e)
  46. {
  47. e.printStackTrace();
  48. } catch (IOException e)
  49. {
  50. e.printStackTrace();
  51. }finally
  52. {
  53. if (fos != null)
  54. {
  55. try
  56. {
  57. fos.flush();
  58. fos.close();
  59. } catch (IOException e)
  60. {
  61. e.printStackTrace();
  62. }
  63. }
  64. }
  65. break;
  66. case R.id.read:
  67. displayView.setText("");
  68. FileInputStream fis = null;
  69. try
  70. {
  71. fis = openFileInput(FILE_NAME);
  72. if (fis.available() == 0)
  73. {
  74. return;
  75. }
  76. byte[] buffer = new byte[fis.available()];
  77. while(fis.read(buffer) != -1)
  78. {
  79. }
  80. String text = new String(buffer);
  81. displayView.setText(text);
  82. labelView.setText(String.format("文件讀取成功,文件長度:%d", text.length()));
  83. } catch (FileNotFoundException e)
  84. {
  85. e.printStackTrace();
  86. } catch (IOException e)
  87. {
  88. e.printStackTrace();
  89. }
  90. break;
  91. }
  92. }
  93. }

Android系統支持四種文件操作模式

MODE_PRIVATE 私有模式,缺陷模式,文件僅能夠被文件創建程序訪問,或具有相同UID的程序訪問。
MODE_APPEND 追加模式,如果文件已經存在,則在文件的結尾處添加新數據。
MODE_WORLD_READABLE 全局讀模式,允許任何程序讀取私有文件。
MODE_WORLD_WRITEABLE 全局寫模式,允許任何程序寫入私有文件。

Copyright © Linux教程網 All Rights Reserved