前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android追加换行写入内容到txt文件中

Android追加换行写入内容到txt文件中

作者头像
程序员飞飞
发布2020-02-27 16:50:17
4K0
发布2020-02-27 16:50:17
举报
文章被收录于专栏:Android&Java技术

#Android追加换行写入内容到txt文件中

实现思路为:使用Context.MODE_APPEND属性将每次内容的写入到上次内容的尾部,然后在每次写入内容完成之后写入一个回车换行符**fos.write("\r\n".getBytes());**即可。

代码语言:javascript
复制
/**
 * Created by xpf on 2017/10/31 :)
 * Function:
 */

public class FileHelper {

    private Context mContext;

    public FileHelper(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 定义文件保存的方法,写入到文件中,所以是输出流
     */
    public void save(String adNum, String time) {
        String content = "广告位编号:" + adNum + ",播放时长:" + time;
        FileOutputStream fos = null;
        try {
            // Context.MODE_PRIVATE私有权限,Context.MODE_APPEND追加写入到已有内容的后面
            fos = mContext.openFileOutput(getFileName(), Context.MODE_APPEND);
            fos.write(content.getBytes());
            fos.write("\r\n".getBytes());//写入换行
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 定义文件读取的方法
     */
    public String read(String filename) throws IOException {
        FileInputStream fis = mContext.openFileInput(filename);
        byte[] buff = new byte[1024];
        StringBuilder sb = new StringBuilder("");
        int len = 0;
        while ((len = fis.read(buff)) > 0) {
            sb.append(new String(buff, 0, len));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * get file name such as 20171031.txt
     *
     * @return
     */
    private String getFileName() {
        return TimeUtil.getCurrentDay() + ".txt";
    }
}

转载请注明出处,谢谢!

本文首发于我的微信公众号,更多干货文章,请扫描二维码订阅哦:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/10/31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档