2015-11-23

【Android Studio】寫入純文字檔

資料來源 ----
儲存檔案
Environment


Android 存放檔案的位置分為 內部外部,若希望儲存的文字檔也要供其他 app 可以存取,或是在解除安裝 app 後仍保留下儲存的檔案,則檔案必須存放在外部公共儲存空間。

AndroidManifest.xml 加入存取外部儲存空間的權限
  1.  
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  3. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  4.  
  5. ...
  6. ...
  7.  
  8. <application
  9.  

  1.  
  2. ...
  3. ...
  4.  
  5. public void onbutton1click(View v)
  6. {
  7. boolean hasExternalStorage = isExternalStorageWritable();
  8. if(hasExternalStorage)
  9. {
  10. // 目前日期
  11. String dateformat = "yyyyMMdd";
  12. SimpleDateFormat df = new SimpleDateFormat(dateformat);
  13. String filename = "tracelog." + df.format(new Date());
  14. Log.d(TAG, "filename == " + filename);
  15.  
  16. File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
  17. File file = new File(path, filename);
  18.  
  19. try
  20. {
  21. path.mkdirs();
  22.  
  23. // 老灰鴨的模擬器是 Genymotion
  24. // 以 Android Device Monitor 觀察
  25. // 存放檔案位置在 /mnt/shell/emulated/0/Download/
  26. OutputStream os = new FileOutputStream(file, true); // 第二個參數為是否 append
  27. // 若為 true,則新加入的文字會接續寫在文字檔的最後
  28. dateformat = "yyyyMMdd kk:mm:ss";
  29. df.applyPattern(dateformat);
  30. String string = "Hello world! " + df.format(new Date()) + "\n";
  31. os.write(string.getBytes());
  32. os.close();
  33. }
  34. catch (IOException e)
  35. {
  36. // Unable to create file, likely because external storage is
  37. // not currently mounted.
  38. Log.w("ExternalStorage", "Error writing " + file, e);
  39. }
  40. }
  41. else
  42. Toast.makeText(this,"no Storage",Toast.LENGTH_SHORT).show();
  43. }
  44.  
  45. public boolean isExternalStorageWritable()
  46. {
  47. String state = Environment.getExternalStorageState();
  48. if (Environment.MEDIA_MOUNTED.equals(state))
  49. {
  50. return true;
  51. }
  52. return false;
  53. }
  54.  
  55.  
  56. ...
  57. ...
  58.  

沒有留言:

張貼留言