ファイル
■openFileOutputによる保存
/data/data/(パッケージ名)/files の中に保存
try{
FileOutputStream file = openFileOutput("sample.txt", MODE_PRIVATE);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(file));
String text="テストです\nどうでしょうか?\n";
bw.write(text);
bw.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
openFileOutput の第二引数
| MODE_PRIVATE | 自アプリのみ使用可能 |
| MODE_APPEND | 追記 |
| MODE_WORLD_READABLE | 他アプリからも読み込み可能 |
| MODE_WORLD_WRITEABLE | 他アプリからも書き込み可能 |
■openFileInputによる読み込み
try{
FileInputStream in=openFileInput("sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String buff;
while((buff = br.readLine())!=null){
sb.append(buff+"\n");
}
br.close();
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText(sb.toString());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
■SDカードの状態確認
String status = Environment.getExternalStorageState();
if(status.equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(this, "SDあり", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "SDなし", Toast.LENGTH_SHORT).show();
}
■SDカードへの保存
String path = Environment.getExternalStorageDirectory().getPath();
String fname = path + "/test.txt";
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(fname));
bw.write("SDカードテスト");
bw.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
AndroidManifest.xml にパーミッション「WRITE_EXTERNAL_STORAGE」を追加
■SDカードからの読み込み
String path = Environment.getExternalStorageDirectory().getPath();
String fname = path + "/test.txt";
try {
BufferedReader br = new BufferedReader(new FileReader(fname));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
EditText ed=(EditText)findViewById(R.id.editText1);
ed.setText(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Android開発 虎の巻