ローカルファイルの内容を読み込む (ローカルファイルからのファイルリード) - Android

ローカルファイルからファイル内容を読み取るコードを紹介します。

アプリケーション

下図のUIを作成します。下図のUIで使用するのはボタン2つ、TextEdit2つのみです。


コード

保存用のボタンのonClickイベント

public void onClick_Button3(View view){
  try{
    EditText et = (EditText)findViewById(R.id.editText1);

    OutputStream os = openFileOutput("memo.txt", MODE_APPEND);
    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

    PrintWriter pw = new PrintWriter(osw);
    String s = et.getText().toString();
    pw.append(s+"\r\n");
    pw.close();

    osw.close();
    os.close();
  }
  catch (FileNotFoundException e){
    e.printStackTrace();   	
  }
  catch (IOException e){
    e.printStackTrace();
  }
}

読み込み用のボタンのonClickイベント

public void onClick_Button4(View view){
  EditText et = (EditText)findViewById(R.id.editText2);
   	 
  try{
    InputStream inputStream = openFileInput("memo.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String s;
    while ((s = bufferedReader.readLine() ) != null){
      et.append(s);
      et.append("\r\n");
    }
  }
  catch(UnsupportedEncodingException e)
  {
    e.printStackTrace();
  }
  catch(FileNotFoundException e)
  {
    e.printStackTrace();
  }
  catch(IOException e)
  {
    e.printStackTrace();
  }
}

実行結果

アプリケーションを実行します。


上のEditText(editText1)に文字を入力します。入力後[Save LocalFile]ボタンを押します。editText1に入力した内容がローカルファイルに保存されます。


[Load LocalFile]ボタンを押します。EditText(editText1)に入力した内容が下のTextEdit(editText2)に表示されます。


著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-04
作成日: 2011-08-23
iPentec all rights reserverd.