[Android Studio] 第19節 保存ファイルの内部ストレージ

目次

1. 保管方法

2. ストアド プロシージャのデポジット

3. ストアド プロシージャの取得

4. openFileOutput() メソッドの複数のモード

1. 保管方法

Android Studio にファイルを保存するには、いくつかの方法があります。一般的なファイル保存方法をいくつか示します。

  1. 内部記憶装置:

    • メソッドを呼び出して、 getFilesDir() アプリケーションの内部ストレージ ディレクトリを取得します。
    • このディレクトリを使用して、アプリケーション自体のみがアクセスできるアプリケーションのプライベート ディレクトリにファイルとディレクトリを作成します。
    • File ファイル操作には Javaクラスまたは Kotlin を使用できます java.io.File 。
  2. 外部記憶装置:

    • メソッドを呼び出して Environment.getExternalStorageDirectory() 外部ストレージ ディレクトリを取得します。
    • 適切な権限を宣言する必要があります (例 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>:
    • Android 10 (API レベル 29) 以降では、外部ストレージ上のファイルにアクセスするには、MediaStore API または SAF (Storage Access Framework) を使用する必要があります。
  3. 共有設定:

    • SharedPreferences を使用すると、少量のキーと値のペアのデータを簡単に保存できます。
    • getSharedPreferences() or メソッドを通じて SharedPreferences オブジェクトを取得しますgetPreferences() 。
    • edit() SharedPreferences オブジェクトのメソッドを 使用して 、編集を開始し、putXxx() メソッドを通じてデータを保存します。
  4. SQLite データベース:

    • 大量の構造化データを保存する必要がある場合は、SQLite データベースを使用できます。
    • テーブルを作成し、モデル クラスを定義し、SQL 操作を実行する必要があります。
    • Android が提供する SQLiteOpenHelper クラスまたはサードパーティ ライブラリを使用して、データベース操作の管理を支援できます。

特定のニーズとデータ量に基づいて、適切なファイル保存方法を選択してください。外部ストレージを使用する場合は、必ず権限の問題に対処し、Android 10 以降でのストレージ アクセスの変更に適応してください。

2. ストアド プロシージャのデポジット

openFileOutput()データを内部ストレージのファイルに保存するには、次のメソッドを使用します。

String filename = "data";
String content = "要存储的内容";

try {
    FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
    fos.write(content.getBytes());
    fos.close();
    // 存储成功
} catch (IOException e) {
    e.printStackTrace();
    // 存储失败,处理异常
}

上記のコードでは次のようになります。

  • openFileOutput() このメソッドは、出力ストリームを開いてファイル名とファイル モードを指定するために使用されます (ここでは、 MODE_PRIVATE 現在のアプリケーションのみがファイルにアクセスできることを示すために使用されています)。
  • write() メソッドはコンテンツをバイト単位で出力ストリームに書き込みます。
  • 最後に、 close() メソッドを通じて出力ストリームを閉じて、データが確実に保存されるようにします。

openFileOutput()でファイルを保存すると、同名のファイルは上書きされますのでご注意ください。元のコンテンツを上書きするのではなく、コンテンツを追加する必要がある場合は、他の方法 ( を使用してopenFileInput()ファイルのコンテンツを読み取り、新しいコンテンツを追加してから再度書き込むなど) を使用してください。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DictionaryTableActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:ignore="MissingConstraints"
        tools:layout_editor_absoluteX="26dp"
        tools:layout_editor_absoluteY="0dp">

        <EditText
            android:id="@+id/edit_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autofillHints="username"
            android:hint="输入内容"
            tools:ignore="MissingConstraints"/>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
public class DictionaryTableActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dictionary_table);
        editText = (EditText) findViewById(R.id.edit_1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String input = editText.getText().toString();
        save(input);
    }

    private void save(String input){
        FileOutputStream fileOutputStream = null;
        BufferedWriter writer = null;
        try {
           fileOutputStream =  openFileOutput("data", Context.MODE_PRIVATE);
           writer =  new BufferedWriter(new OutputStreamWriter(fileOutputStream));
           writer.write(input);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (writer != null){
                    writer.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

3. ストアド プロシージャの取得


public class DictionaryTableActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dictionary_table);
   
     
        editText = (EditText) findViewById(R.id.edit_1);
        editText.setText(load());
        editText.setSelection(load().length());
    }

  
    private String load(){
        FileInputStream fileInputStream = null;
        BufferedReader reader = null;
        StringBuilder stringBuffer = new StringBuilder();
        try {
            fileInputStream = openFileInput("data");
            reader  =  new BufferedReader(new InputStreamReader(fileInputStream));
            String Line ="";
            while ( (Line = reader.readLine()) != null){
                stringBuffer.append(Line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                assert reader != null;
                reader.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }

4.openFileOutput()メソッドの複数モード ( mode)

よく使用されるモードと注意事項:

  1. MODE_PRIVATE

    • パターン定数:0 または Context.MODE_PRIVATE
    • 現在のアプリケーションのみがファイルにアクセスできます。
    • 指定したファイルが存在しない場合は新しいファイルが作成され、ファイルが既に存在する場合は元の内容が上書きされます。
    • 他のアプリケーションがアクセスできなくなるため、重要な機密データを MODE_PRIVATE スキーマを含むファイルに保存しないように注意してください。
  2. MODE_APPEND

    • モード定数:Context.MODE_APPEND
    • ファイルを書き込むときに、元のコンテンツを上書きせずにコンテンツを追加します。
    • 指定したファイルが存在しない場合は、新しいファイルが作成されます。
    • 既存のファイルの末尾にデータを追加する必要があるシナリオに適しています。
  3. MODE_WORLD_READABLE

    • モード定数:Context.MODE_WORLD_READABLE
    • 他のアプリケーションがファイルを読み取ることを許可します。
    • このモードは、データ漏洩やセキュリティの問題につながる可能性があるため、推奨されません。
    • このモードは Android 7.0 以降ではサポートされていません。
  4. MODE_WORLD_WRITEABLE

    • モード定数:Context.MODE_WORLD_WRITEABLE
    • 他のアプリケーションがファイルに書き込むことを許可します。
    • このモードは、データ漏洩やセキュリティの問題につながる可能性があるため、推奨されません。
    • このモードは Android 7.0 以降ではサポートされていません。

ストレージ モードを選択するときは、特定のニーズとセキュリティの考慮事項に基づいて選択してください。MODE_WORLD_READABLEデータのセキュリティを保護するために、使用を避けてくださいMODE_WORLD_WRITEABLE元のコンテンツを上書きせずにコンテンツを追加する必要がある場合は、MODE_APPENDモードを使用できます。通常のプライベート ファイルの場合は、デフォルトを使用することでMODE_PRIVATEほとんどの状況のニーズを満たすことができます。

おすすめ

転載: blog.csdn.net/AA2534193348/article/details/131493806