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

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

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

接下來就到SD卡了吧 ^_^

不是所有的手機都有SD卡,但是Android系統本身提供了對SD卡很便捷的訪問方法

相關閱讀:

[Android SQLite]數據存儲與訪問 - 內部存儲 http://www.linuxidc.com/Linux/2011-12/50130.htm

[Android SQLite]數據存儲與訪問 - SharedPreferences http://www.linuxidc.com/Linux/2011-12/50131.htm

一般下載的數據都比較大就都放到SD卡了...具體原因,未知 哈哈

  1. public class SD_Demo extends Activity implements OnClickListener
  2. {
  3. private StringBuilder randomNumBersString = null;
  4. private TextView displayView = null;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState)
  7. {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.main1);
  10. setupViews();
  11. }
  12. private void setupViews()
  13. {
  14. displayView = (TextView) findViewById(R.id.display);
  15. findViewById(R.id.random).setOnClickListener(this);
  16. findViewById(R.id.write).setOnClickListener(this);
  17. randomNumBersString = new StringBuilder();
  18. }
  19. @Override
  20. public void onClick(View v)
  21. {
  22. switch (v.getId())
  23. {
  24. case R.id.random:
  25. for (int i = 0; i < 10; i++)
  26. {
  27. randomNumBersString.append(Math.random()+"\n");
  28. }
  29. displayView.setText(randomNumBersString.toString());
  30. break;
  31. case R.id.write:
  32. String fileName = "SdcardFile-"+System.currentTimeMillis()+".txt";;
  33. boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
  34. File dir = null;
  35. if (sdCardExist)
  36. {
  37. dir = new File( Environment.getExternalStorageDirectory().toString() + File.separator + "123321");
  38. if (!dir.exists())
  39. {
  40. dir.mkdirs();
  41. }
  42. }
  43. if (dir.exists() && dir.canWrite())
  44. {
  45. File newFile = new File(dir.getAbsolutePath()+ "/" + fileName);
  46. FileOutputStream fos = null;
  47. try
  48. {
  49. newFile.createNewFile();
  50. if (newFile.exists() && newFile.canWrite())
  51. {
  52. fos = new FileOutputStream(newFile);
  53. fos.write(randomNumBersString.toString().getBytes());
  54. displayView.setText(String.format("%s文件寫入SD卡", fileName)) ;
  55. }
  56. } catch (IOException e)
  57. {
  58. e.printStackTrace();
  59. }finally
  60. {
  61. if (fos != null)
  62. {
  63. try
  64. {
  65. fos.flush();
  66. fos.close();
  67. } catch (IOException e)
  68. {
  69. e.printStackTrace();
  70. }
  71. }
  72. }
  73. }
  74. break;
  75. }
  76. }
  77. }
很有價值的參考文章 http://www.linuxidc.com/Linux/2011-02/32603.htm
Copyright © Linux教程網 All Rights Reserved