android 存储 累加内容到文件的txt文本

/**
 * 保存动作数据
 * data 保存的内容
 * time 时间作为txt文件名
 */
private void saveAction(String data, String time) {
    //新建文件夹
    String folderName = "A-Bluetooth";
    File sdCardDir = new File(Environment.getExternalStorageDirectory(), folderName);
    if (!sdCardDir.exists()) {
        if (!sdCardDir.mkdirs()) {
            try {
                sdCardDir.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    Log.i(TAG, "记录所有数据时间: " + time);
    String fileName = time + ".csv";

    //新建文件
    File saveFile = new File(sdCardDir, fileName);
    try {
        if (!saveFile.exists()) {
            saveFile.createNewFile();
        }
       writeData(data, false, saveFile);
    } catch (Exception e) {
        Log.i(TAG, "saveAll: " + e.toString());
    }

}

 

/**
 * @param content        写入内容
 * @param isClearContent 是否清楚原来内容 true 覆盖数据 false 累加内容
 */
//每次都重新写入
public void writeData(String content, Boolean isClearContent, File saveFile) {
    try {
        if (isClearContent) {
            final FileOutputStream outStream = new FileOutputStream(saveFile);
            try {
                //内容写入文件
                outStream.write(content.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "writeTxtToFile: --------------" + e.toString());
            } finally {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            //内容追加

            BufferedWriter out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(saveFile, true)));
                out.write(content + "\r\n");
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Toast.makeText(mContext, "写入成功", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

遥不可及zzz

我会用心写更多自己的经验。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值