2013年4月9日 星期二

[android]在 sdcard 寫檔案

首先要 WRITE_EXTERNAL_STORAGE 的 permission。所以要到 AndroidManfest.xml 加入設定。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

再來就是範例,我希望有 BufferedWriter 可以增進效率,但是,目前我還沒寫好配套措施,所以現在看起來很笨。先將就著用…。

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

public class MyFile {
    private String _filename = "";
    private File _filehandle = null;
    private String TAG = this.getClass().getName();
//    private int writecount=0;
//    private int writeubound=200;

    public MyFile(String filename) {
        this._filename = filename;
    }

    public void write(String content) {
        if (this._filehandle == null) {
            File root = Environment.getExternalStorageDirectory();
            this._filehandle = new File(root, this._filename);
        }
        try {
            FileWriter filewriter = new FileWriter(this._filehandle, true);
            BufferedWriter out = new BufferedWriter(filewriter);
            out.write(content);
//            writecount +=1;
//            if(writecount>writeubound){
//               
//            }
            out.flush();
            out.close();
        } catch (IOException e) {
            Log.d(TAG, "write failed");
        }
    }
//    public void close(){
//        if (this._filehandle!=null){}
//    }
}

 

完畢。

沒有留言:

張貼留言