テキストファイルの読み書き
openFileInput, openFileOutput, fileListを使う
ファイルはどこにできているんだろう。
package org.shokai.test; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.*; import android.view.*; import android.view.View.OnClickListener; import android.widget.*; import java.io.OutputStream; import java.util.*; import java.io.*; public class Test extends Activity implements OnClickListener{ private Button buttonList, buttonSave, buttonLoad; private TextView textView; private EditText editText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.buttonList = (Button) this.findViewById(R.id.ButtonList); this.buttonSave = (Button) this.findViewById(R.id.ButtonSave); this.buttonLoad = (Button) this.findViewById(R.id.ButtonLoad); this.textView = (TextView) this.findViewById(R.id.TextView); this.editText = (EditText) this.findViewById(R.id.EditText); this.buttonList.setOnClickListener(this); this.buttonLoad.setOnClickListener(this); this.buttonSave.setOnClickListener(this); } public void onClick(View v) { switch(v.getId()){ case R.id.ButtonList : Log.v("buttonList", "ファイルのリスト"); String[] files = this.fileList(); String str = ""; for(int i = 0; i < files.length; i++){ str += files[i]; if(i < files.length-1) str += ", "; } textView.setText(str); break; case R.id.ButtonSave : Log.v("buttonSave", "書き込み開始"); try{ saveStr("tmp2.txt", editText.getText().toString()); } catch(Exception e){ Log.e("saveStr", e.toString()); } break; case R.id.ButtonLoad : Log.v("buttonLoad", "読み出し開始"); try{ editText.setText(loadStr("tmp2.txt")); } catch(Exception e){ Log.e("loadStr", e.toString()); } break; } } // ファイル名を指定して開く public String loadStr(String fileName) throws Exception{ try{ InputStream is = this.openFileInput(fileName); byte[] bytes = new byte[is.available()]; is.read(bytes); is.close(); return new String(bytes); } catch(Exception e){ throw e; } } // ファイル名を指定して保存 public void saveStr(String fileName, String str) throws Exception{ try{ OutputStream os = this.openFileOutput(fileName, Context.MODE_PRIVATE); os.write(str.getBytes()); os.close(); } catch(Exception e){ throw e; } } }