Apache commons-io


添加引用

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>


按行写:

    public static void writeFileLineByApacheIO(String fileContent) throws IOException {
        String fileName = "";
        String nowday = DateUtil.getNowDayString();
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            fileName = "C:\\log\\" + nowday + ".txt";
        } else {
            fileName = "//log//" + nowday + ".txt";
        }
        File file = new File(fileName);
        List<String> lines=new ArrayList<String>();
        lines.add(fileContent);
        FileUtils.writeLines(file,"UTF-8",lines,true);
    } 

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DateUtil {

    //返回当前时间
    public static String getNowTimeString() {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        return time;
    }

    //设置日期格式
    public static String getNowDayString() {
        SimpleDateFormat dfday = new SimpleDateFormat("yyyy-MM-dd");
        String nowday=dfday.format(new Date());
        return nowday;
    }
}


注意还有个writeStringToFile需要自己手动添加换行不然连在一起了。


FileUtils.writeStringToFile和FileUtils.writeLines如果不加true就是替换而不是增量写

参考:

使用FileUtils简化你的文件操作

Apache Commons工具集简介

你可能感兴趣的:(Apache commons-io)