【Android】ファイルの読み込み、保存

環境

  • OSX Yosemite v10.10.5
  • AndroidStudio v1.3.2

openFileInput()
openFileOutput()

private final static String LOCAL_FILE = "test.txt";

/**
 * 読み込み
 */
private void sampleOpenFileInput(){
    InputStream in;
    try {
        in = openFileInput(LOCAL_FILE);
        InputStreamReader isr = new InputStreamReader(in, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        br.read();
        br.close();
    } catch (Exception e) {
    }
}

/**
 * 保存
 */
private void sampleOpenFileOutput(){
    OutputStream out;
    try {
        out = openFileOutput(LOCAL_FILE, MODE_PRIVATE | MODE_APPEND);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(out,"UTF-8"));
        writer.append("write test");
        writer.close();
    } catch (Exception e) {
    }
}

BufferedReader.read()
BufferedWriter.write()

private final static String filePath = Environment.getExternalStorageDirectory() + "/test.txt";
private File file = new File(filePath);

/**
 * 読み込み
 */
private void sampleFileInputStream(){
    file.getParentFile().mkdir();

    FileInputStream fis;
    try {
        fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        br.read();
        br.close();
    } catch (Exception e) {
    }
};

/**
 * 保存
 */
private void sampleFileOutputStream(){
    file.getParentFile().mkdir();

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(file, true);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        String str = "test";
        bw.write(str);
        bw.flush();
        bw.close();
    } catch (Exception e) {
    }
};