SDカードにテキストデータを書き込むサンプル。
画面は一つのEditTextViewと一つのButtonから構成されており、
Buttonを押すとEditTextViewに入力された内容をSDカードに書き込んでいる。
package com.lesson.sdcard; // インポートは省略 public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final String PATH = Environment.getExternalStorageDirectory().toString() + File.separator + this.getPackageName(); Log.d(getPackageName(), "Path:" + PATH); findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // SDカードのパスをチェック File f = new File(PATH); if( !f.exists() && !f.mkdir() ){ return; } final String fileName = PATH + File.separator + "test.txt"; OutputStreamWriter osw = null; try { osw = new OutputStreamWriter(new FileOutputStream(fileName)); CharSequence txt = ((EditText)findViewById(R.id.editText1)).getText(); osw.write(txt.toString(),0,txt.length()); } catch (FileNotFoundException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } catch (IOException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } finally{ try { if( osw != null ) osw.close(); } catch (IOException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } osw = null; } } }); } }
ボタンを押すと、
/mnt/sdcard/com.lesson.sdcard/
以下にtext.txtという名前でファイルが保存される。