ウェブアプリケーション,インジェクション,コマンドインジェクション

Androidアプリ開発 データを持続させる

キャッシュディレクトリにファイルを保存

Saving Files to the Cache Directory

filesフォルダに保存されたファイルは持続的です。
それらのファイルは明らかな削除の操作をしなければ
フォルダにあり続けます。
しかし、一時的に保存したいだけの場合や、もう一度使うことがない、
などの理由で持続的に保存したくない場合が時にはあるかもしれません。
こんな時には、cacheフォルダを使ってファイルを一時的に保存します。


ちょっと注釈

cacheフォルダに保存されたファイルは永続的ではありません。
内部ストレージがローの時にOSで削除されます。
しかし、OSまかせにするのではなく、コンピュータの使用者自身で
このフォルダを習慣的にきれいにするのが良く、
1MB以上アプリケーションに使わせないようにするほうが良いでしょう。


cacheディレクトリにファイルを保存するためには、
getCacheDir()メソッドを使い、ファイルシステムのアプリケーションが
指定するcacheディレクトリに絶対パズを返します。
cacheフォルダに保存したいファイルの完全なパスを作るために
Fileクラスを使うことができます。
以下のコードはcacheフォルダの中にファイルを保存し、
その時にそのファイルの内容を読み戻す方法を示します。

package net.learn2develop.cache;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.InputStreamReader;
import java.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toase;

public class MainActivity extends Activity{
  static final int READ_BLOCK_SIZE = 100;
  @Override
  public void onCreate(Bundle savedInstanceState){
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   //---Saving to the file in the Cache folder---
   try{
    //---get the Cache derectory---
    File cacheDir = getCacheDir();
    File file = new File(cacheDir.getAbsolutePath(), "textfile.txt");

    FileOutputStream fOut = new FileOutputStream(file);
    OutputStreamWriter osw = new OutputStreamWriter(fOut);

    //---write the string to the file---
    osw.write("書き込みたい文字列を入力します");
    osw.flush();
    osw.close();

    //---display file saved message---
    Toast.makeText(getBaseContext(), !File saved successfully",
        Toast.LENGTH_SHORT).show();
   }catch(IOException ioe){
    iow.printStackTrace();
   }

   //---Reading from the file in the Cache folder---
   try{
    //---get the Cache directory---
    File cacheDir = getCacheDir();
    File file = new File(cacheDir, "textfile.txt");
    FileInputStream fIn = new FileInputStream(file);

    InputStreamReader isr = new InputStreamReader(fIn);

    char[] inputBuffer = new char[READ_BLOCK_SIZE];
    String s = "";
    int charRead;
    while((charRead = isr.read(inputBuffer)) > 0){
     //---convert the chars to a String---
     String readString = String.copyValueOf(inputBuffer, 0, charRead);
 s += readString;

     inputBuffer = new char[READ_BLOCK_SIZE];
    }

    Toast.makeText(getBaseContext(), "File loaded successfully" + s
       Toast.LENGTH_SHORT).show();
   }catch(IOException ioe){
    ioe.printStackTrace();
   }
  }
}

上のコードが実行されたときには、textfile.txtファイルが
/data/data/<パッケージ名>/cacheフォルダに作られます。

  
ホーム
便利堂ロゴ
inserted by FC2 system