2015-11-23

【Android Studio】寫入純文字檔

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


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

AndroidManifest.xml 加入存取外部儲存空間的權限
 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

...
...

<application
 

 
...
...

public void onbutton1click(View v)
{
    boolean hasExternalStorage = isExternalStorageWritable();
    if(hasExternalStorage)
        {
            // 目前日期
            String dateformat = "yyyyMMdd";
            SimpleDateFormat df = new SimpleDateFormat(dateformat);
            String filename = "tracelog." + df.format(new Date());
            Log.d(TAG, "filename == " + filename);

            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(path, filename);

            try
            {
                path.mkdirs();

                // 老灰鴨的模擬器是 Genymotion
                // 以 Android Device Monitor 觀察
                // 存放檔案位置在 /mnt/shell/emulated/0/Download/
                OutputStream os = new FileOutputStream(file, true);    // 第二個參數為是否 append
                                                                       // 若為 true,則新加入的文字會接續寫在文字檔的最後
                dateformat = "yyyyMMdd kk:mm:ss";
                df.applyPattern(dateformat);
                String string = "Hello world! " + df.format(new Date()) + "\n";
                os.write(string.getBytes());
                os.close();
            }
            catch (IOException e)
            {
                // Unable to create file, likely because external storage is
                // not currently mounted.
                Log.w("ExternalStorage", "Error writing " + file, e);
            }
        }
    else
        Toast.makeText(this,"no Storage",Toast.LENGTH_SHORT).show();
}

public boolean isExternalStorageWritable() 
{
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) 
    {
        return true;
    }
    return false;
}


...
...
 

沒有留言:

張貼留言