使用java的io流编写日志类

博客来源:

编写项目的时候需要打印日志保存到本地,由于控制台输出不容易监控,可以进行日志打印

话不多说,上代码

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

/**
 * Created by CXC on 2017/6/5.
 */
public class MyLogs {
    /**
     * @将错误信息输入到txt中
     * @param str 存储的路径,name 保存的名字,content 保存的值
     * @throws IOException
     */
    public void writeEror_to_txt(String str ,String name,String content){
    	//因为要生成日志、所以固定
    	if(str==null)
    		str = System.getProperty("user.dir");
        File F=new File(str , name);
        //如果文件不存在,就动态创建文件
        if(!F.exists()){
            try {
				F.createNewFile();
			} catch (IOException e) {
			}
        }
       
        FileWriter fw=null;
        String writeDate=content;
        try {
            //设置为:True,表示写入的时候追加数据
            fw=new FileWriter(F, true);
            //回车并换行
            fw.write(writeDate+"\r\n");
        } catch (IOException e) {
        }finally{
            if(fw!=null){
                try {
					fw.close();
				} catch (IOException e) {
				}
            }
        }

    }
    /**
     * @获取系统当前时间
     * @return
     */
    public static String get_nowDate(){

        Calendar D=Calendar.getInstance();
        int year=0;
        int moth=0;
        int day=0;
        int hour=0;
        int minute=0;
        int second=0;
        year=D.get(Calendar.YEAR);
        moth=D.get(Calendar.MONTH)+1;
        day=D.get(Calendar.DAY_OF_MONTH);
        hour=D.get(Calendar.HOUR_OF_DAY);
        minute=D.get(Calendar.MINUTE);
        second=D.get(Calendar.SECOND);
        String now_date=checkNum(year)+"-"+checkNum(moth)+"-"+checkNum(day)+" "
        +checkNum(hour)+":"+checkNum(minute)+":"+checkNum(second);
        return now_date;
    }
    
    /**
     * @获取系统当前时间 年-月-日
     * @return
     */
    public static String get_Date(){

        Calendar D=Calendar.getInstance();
        int year=0;
        int moth=0;
        int day=0;
        year=D.get(Calendar.YEAR);
        moth=D.get(Calendar.MONTH)+1;
        day=D.get(Calendar.DAY_OF_MONTH);
        return checkNum(year)+"-"+checkNum(moth)+"-"+checkNum(day);
    }
    
    private static String checkNum(int num) {
    	if(num<10) {
    		return "0"+num;
    	}
    	return String.valueOf(num);
    }
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值