CSV 出力
ポイント1 パスは Environment.getExternalStorageDirectory() で取得。
機種によって違うから。
ポイント2 fos = new FileOutputStream(file,false);//true 追加モード false 上書き
ポイント3 //改行があるとレコードが分裂してしまうため改行を除去する。
str = "111122\n222222";
str = str.replaceAll("\n", " ")+"\n";
ポイント4 例外処理をいれる
catch (Exception e) { //例外処理
}
String filePath = Environment.getExternalStorageDirectory() + "/ddata.txt";
File file = new File(filePath);
file.getParentFile().mkdir();
FileOutputStream fos;
String str = "";
try {
fos = new FileOutputStream(file,false);//true 追加モード false 上書きモード
//fos = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
//改行があるとレコードが分裂してしまうため改行を除去する。
str = "111122\n222222";
str = str.replaceAll("\n", " ")+"\n";
bw.write(str);
str = "tesutotttt";
str = str.replaceAll("\n", " ")+"\n";
bw.write(str);
str = "2\n2222222";
str = str.replaceAll("\n", " ")+"\n";
bw.write(str);
//bw.flush();
bw.close();
AlertDialog.Builder ad2 = new AlertDialog.Builder(MainActivity.this);
// ダイアログの設定
// alertDialog.setIcon(R.drawable.icon); //アイコン設定
ad2.setIcon(R.drawable.ic_launcher);
ad2.setTitle("CSVファイル出力"); //タイトル設定
ad2.setMessage(filePath+" を作成しました。このファイルをGoogleドライブなどに保管すれば他のパソコンから参照できます。"); //内容(メッセージ)設定
// OK(肯定的な)ボタンの設定
ad2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// OKボタン押下時の処理
//処理が止まらないのでOK押させるだけ
}
});
// ダイアログの作成と描画
ad2.show();
} catch (Exception e) { //例外処理
AlertDialog.Builder ad2 = new AlertDialog.Builder(MainActivity.this);
// ダイアログの設定
// alertDialog.setIcon(R.drawable.icon); //アイコン設定
ad2.setIcon(R.drawable.ic_launcher);
ad2.setTitle("ファイル入出力エラー"); //タイトル設定
ad2.setMessage("ディスクエラーや、容量不足など・・・"); //内容(メッセージ)設定
// OK(肯定的な)ボタンの設定
ad2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// OKボタン押下時の処理
//処理が止まらないのでOK押させるだけ
}
});
// ダイアログの作成と描画
ad2.show();
}
File file = new File("mnt/sdcard", "data");
みたいにそのpathを絶対的に指定することはできません。なんとかしてその機種固有のpathを取得する必要があります。
その為に用意されていたのが、
Environment.getExternalStorageDirectory()
しかし、
Androidでは、ストレージ(SDカードなど)のパスを取得するために Environment.getExternalStorageDirectory() が用意されています。
しかし、ストレージが内部ストレージ(取外不可)と外部ストレージ(取外可能)に別れている場合、内部ストレージを取得します。
外部は難しいので、内部に保存する。2013/12/15