日志文件工具类

package nc.itf.mm.mes.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;


public class MESLooger {

	private static String fileLoggerPath = "E://MESLooger//logger.txt";
 
	public static void main(String[] args) throws IOException {
		
		StringBuffer sb = new StringBuffer();
		sb.append("你好sss");
		sb.append("\r\n");
		sb.append("sbsvss");
		writeTxtFile(sb.toString());
	}
	
	/**
	 * 写入日志信息
	 * @param errorInfo
	 */
	public static void writeTxtFile(String errorInfo) {

		FileWriter fw = null;
		try {
			File file = new File(fileLoggerPath);
			if (!file.exists()) {
				File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
			}else{
//				FileOutputStream testfile = new FileOutputStream(fileLoggerPath);
//				testfile.write(new String("").getBytes());
				
				long fileSize = getFileSize(file);
				long maxsiez =  52428800;//设定50M
				if(maxsiez<=fileSize){
					FileWriter fileWriter =new FileWriter(file);
		            fileWriter.write("");
		            fileWriter.flush();
		            fileWriter.close();
				}
				
			}
			
			
			String str = readTxtFile(new File(fileLoggerPath));
			fw = new FileWriter(fileLoggerPath);
			if (str.length() < 1) {
				fw.write(errorInfo);
			} else {
				fw.write(str + "\r\n" + errorInfo);
			}
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
			try {
				fw.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

	}
	
	/*
	 * 获取文件大小的方法02:
	 * 通过FileChannel类来获取文件大小,这个方法通常结合输入流相关,
	 * 因此可以用于文件网络传输时实时计算文件大小;
	 * */ 
	private static long getFileSize(File file) throws IOException {
		FileInputStream fis = new FileInputStream(file);
		FileChannel fc = fis.getChannel();
		return fc.size();
	}
	
	/**
	 * 读取原文件内容
	 * @param f
	 * @return
	 * @throws IOException
	 */
	public static String readTxtFile(File f) throws IOException {
		String strs = "";
		try {
			@SuppressWarnings("resource")
			FileReader read = new FileReader(f);
			StringBuffer sb = new StringBuffer();
			char ch[] = new char[1024];
			int d = read.read(ch);
			while (d != -1) {
				String str = new String(ch, 0, d);
				sb.append(str);
				d = read.read(ch);
			}

			strs = sb.toString();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return strs;
	}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值