@blog.justoneplanet.info

日々勉強

androidでローカルファイルにアクセスする

■読込

try {
    InputStream inputStream = openFileInput(FILENAME);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    String str;
    while((str = reader.readLine()) != null) {
    }
    reader.close();
    inputStream.close();
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}

■書込

try {
    OutputStream outputStream = openFileOutput(FILENAME, MODE_PRIVATE);
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
    printWriter.append(str);
    printWriter.close();
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

非同期

巨大なファイルの場合に同期読込がANRを発生させることがある。従って、AsyncTaskを使って非同期にファイルの読込書込を行う。

AsyncFileReadTask.java
package info.justoneplanet.android.sample.localfile;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.os.AsyncTask;

public class AsyncFileReadTask extends AsyncTask<String, String, String> {
    
    private Context mContext;
    private Observer mObserver;

    AsyncFileReadTask(Context context, Observer observer) {
        mContext = context;
        mObserver = observer;
    }

    @Override
    protected String doInBackground(String... params) {
        String data = "";
        try {
            InputStream inputStream = mContext.openFileInput(params[0]);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String str;
            while((str = reader.readLine()) != null) {
                data += str;
            }
            reader.close();
            inputStream.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
    
    @Override
    protected void onPostExecute(String result) {
        mObserver.onReadFile(result);
    }
    
    public interface Observer {
        public void onReadFile(String result);
    }
}
AsyncFileWriteTask.java
package info.justoneplanet.android.sample.localfile;

import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import android.content.Context;
import android.os.AsyncTask;

public class AsyncFileWriteTask extends AsyncTask<String, String, Boolean> {

    private Context mContext;
    private Observer mObserver;

    AsyncFileWriteTask(Context context, Observer observer) {
        mContext = context;
        mObserver = observer;
    }
    
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            OutputStream outputStream = mContext.openFileOutput(params[0], Context.MODE_PRIVATE);
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            printWriter.append(params[1]);
            printWriter.close();
            return Boolean.TRUE;
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Boolean.FALSE;
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
        mObserver.onWriteFile(result);
    }
    
    public interface Observer {
        public void onWriteFile(Boolean result);
    }
}
クライアントコード

上述の2つのクラスは以下のように使用する。

package info.justoneplanet.android.sample.localfile;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;

public class LocalFileActivity extends Activity implements AsyncFileReadTask.Observer, AsyncFileWriteTask.Observer {
    
    private static final String FILENAME = "sample.txt";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // ファイルの読込
        AsyncFileReadTask task = new AsyncFileReadTask(getApplicationContext(), this);
        task.execute(FILENAME);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        
        EditText editText = (EditText) findViewById(R.id.edit_text);
        String str = editText.getText().toString();
        if (str.length() == 0) {
            deleteFile(FILENAME);
            return;
        }
        
        // ファイルの書込
        AsyncFileWriteTask task = new AsyncFileWriteTask(getApplicationContext(), this);
        task.execute(FILENAME, str);
    }

    @Override
    public void onReadFile(String result) {
        EditText editText = (EditText) findViewById(R.id.edit_text);
        editText.append(result);
    }

    @Override
    public void onWriteFile(Boolean result) {
        Log.e("file", "written");
    }
}

■削除

deleteFile(FILENAME);

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment