java持续添加内容至本地文件

package com.lcc.commons;

import com.lcc.commons.dto.FileLogDTO;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * Created by liucongcong on 2018/1/17.
 */

/**
 * 持久化示例。如何将内存中的数据保存起来,并没有一定的格式,任何人 
 * 都可以根据自己的喜好来制定。持久化需要文件操作,所以请务必先弄懂 
 * 如何读写文件。 
 */
public class FileLogUtil {

    // 文件名可随意指定,你可以用文本编辑器打开这个文件(注意,记事本无法处理换行)  
    static String filename = "C:/Users/liucongcong/FileLogDTOs.data";

    public static void main(String[] args) throws Exception {
        appendMethodB(filename);
    }

    public static void appendMethodB(String fileName) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            List<FileLogDTO> result = new ArrayList<FileLogDTO>();
            result.add(new FileLogDTO("张三", new Date(), "成功"));
            result.add(new FileLogDTO("李四", new Date(), "成功"));
            result.add(new FileLogDTO("王五", new Date(), "失败"));
            String data = "";
            for (FileLogDTO FileLogDTO : result) {
                data += getFileLogDTOString(FileLogDTO) + "\n";
            }
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(data);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getFileLogDTOString(FileLogDTO FileLogDTO) {
        return FileLogDTO.getOperater() + "\t" + FileLogDTO.getOperateDate() + "\t" + FileLogDTO.getMessage();
    }
}

 

posted @ 2018-01-19 10:35  growthofmonkey  阅读(1939)  评论(0编辑  收藏  举报