Tips

Android データ入出力と永続化 内部保存域 【Android Tips】

内部保存域

8-2
データ入出力と永続化
内部保存域
今回は内部保存域について解説していきます。
内部保存域について
今回はAndroid端末の内部保存域にデータを保存したり、保存してあるデータを読み込む方法について解説していきます。

内部保存域とはデバイスメモリの事で、OS(Android)がインストールされている場所です。内部保存域に保存したデータはデフォルトでは他のアプリケーションからアクセスすることはできません。プリファレンスと同様にroot化された端末では、他のアプリケーションからアクセスすることが可能となります。エミュレータでも可能です。

内部保存域の保存先は「data/data/パッケージ名/files/」です。
保存されたデータはアプリケーションを削除すると、すべて破棄されます。

 

それでは以下のコードを確認してください。

データを書き込む場合

1
2
String fname = "hello_file";
FileOutputStream fos = openFileOutput(fname, Context.MODE_PRIVATE);

2行目のopenFileOutput()の第1引数で書き込みを行うファイル名を指定します。ここでは1行目で用意したString型のfnameという変数に代入している「hello_file」を指定しています。openFileOutput()の戻り値には、FileOutputStreamクラスのインスタンス(java.io.FileOutputStream オブジェクト)が返されます。このオブジェクトを使えば文字データやバイナリデータをファイルに書き込むことができます。

また、openFileOutput()の第2引数は共有モードで以下の値を指定します。

定数名 概要
MODE_WORLD_READABLE 他のアプリケーションから読み取り可能
MODE_WORLD_WRITEABLE 他のアプリケーションから書き込み可能
MODE_PRIVATE 他のアプリケーションからアクセス不可


データを読み込む場合

1
2
String fname = "hello_file";
FileInputStream fis = openFileInput(fname);

2行目でファイル名を指定して、読み込むファイルを展開しています。
openFileOutput()と異なり、引数は1つです。
openFileInput()の戻り値には、FileInputStreamクラスのインスタンス(java.io.FileInputStream オブジェクト)が返されます。このオブジェクトを使えば文字データやバイナリデータをファイルから読み込むことができます。

内部保存域のサンプルコード
それではサンプルコードを実際に動かしながら確認していきましょう。
activity_main.xml(レイアウトファイル)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="名前を入力してください。" />
 
    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登録" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="参照" />
 
</LinearLayout>

MainActivity.java(Activityファイル)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.example.instoragesample;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    private String frame = "hello_file";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                EditText editText = (EditText) findViewById(R.id.editText1);
                String str = editText.getText().toString();
 
                FileOutputStream fos = null;
 
                try {
                    fos = openFileOutput(frame, Context.MODE_PRIVATE);
                    fos.write(str.getBytes());
                    Toast.makeText(MainActivity.this, str + "さんを登録しました。", Toast.LENGTH_SHORT).show();
 
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "登録できませんでした。", Toast.LENGTH_SHORT).show();
 
                } finally {
 
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
 
        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                FileInputStream fis = null;
 
                try {
                    fis = openFileInput(frame);
                    byte buffer[] = new byte[100];
                    fis.read(buffer);
                    String str = new String(buffer).trim();
                    Toast.makeText(MainActivity.this, str + "さんが登録されています。", Toast.LENGTH_SHORT).show();
 
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "読み込みに失敗しました。。", Toast.LENGTH_SHORT).show();
 
                } finally {
 
                    try {
                        if (fis != null)
                            fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
 
                }
 
            }
        });
    }
 
}

このサンプルコードではButtonを2つ設置しています。
1つ目はEditTextに入力した内容を登録する為のButtonで、2つ目は保存されているデータを呼び出すためのButtonです。

  • データの書き込み処理
  • 36行目でデータを書き込むファイル名と共有モードを指定しています。
    37行目でEditTextに入力された内容を、String型に変換し、write()で書き込み処理を行っています。
    write()の引数はbyte型の配列なので、getBytes()でString型の文字列をbyte型の配列に変換しています。

    1
    write(byte[] b)

    最後に48行目でFileOutputStremを閉じて終了となります。

  • データの読み込み処理
  • 64行目で読み込みたいデータが入っているファイル名を指定しています。
    65行目では、byte型の配列であるbuffer[]を用意していますが、これは66行目のread()が、読み込んだデータをそのままbyte配列にコピーしてくれるからです。

    1
    read(byte[] b)

    67行目でString型に変換していますが、ここでのtrim()は文字列の先頭または最後に空白が付いている際に、それを削除するためのメソッドです。
    最後に78行目でFileInputStremを閉じて終了となります。

上記サンプルコードは、名前を入力し登録ボタンをクリックすると下図の2枚目のようになります。また、参照ボタンをクリックすると下図の3枚目のようになります。


 

エミュレータの下記フォルダにhello_fileという名前のファイルが作成されます。
「data/data/com.example.instoragesample/files/」

 

出力したファイルを展開すると、登録した「Sato」が保存されているのが確認できます。

1
Sato
 

以上が内部保存域の保存方法です。

Androidアプリ開発の必須知識!JAVAプログラミングを学べる連載リンク

はじめてのJAVA 連載

Recent News

Recent Tips

Tag Search