【Knowledge】知识问答服务器器(日志操作类)

本文介绍了一个简单的日志管理系统,该系统可以记录用户操作信息,并当单个日志文件大小超过1MB时进行压缩归档。系统支持多个日志文件轮转,并在达到指定数量后清理旧文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 日志类,将用户的操作信息写入日志文件中
 */
public class MyLogger {
	private static int index = 1;

	public static void output(String msg){
		try {
			File file = new File("wp"+index+".log");
			PrintStream ps = new PrintStream(new FileOutputStream(file,true));
			while(file.length()>=1024*1024){
				ps.close();
				//文件大于1M了就压缩
				System.out.println(index+"zip...");
				File[] fs = new File[index];
				for (int i = 0; i < fs.length; i++) {
					fs[i] = new File("wp"+(i+1)+".log");
				}
				zip(fs);
				index++;
				//3个日志文件全部写满,如果大于3个就压缩完后删掉
				if(index>3){
					for (int i = 0; i < fs.length; i++) {
						fs[i].delete();
					}
					index = 1;
				}
				//重新定义输出流
				file = new File("wp"+index+".log");
				ps = new PrintStream(new FileOutputStream(file,true));
			}
			ps.println(msg);
			ps.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @param fs
	 * 压缩方法
	 */
	public static void zip(File[] fs){
		try {
			InputStream is = null;
			ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("wp.zip"));
			
			for (int i = 0; i < fs.length; i++) {
			    is = new FileInputStream(fs[i]);
				//构建一个条目,并放入压缩输出流中
				ZipEntry ze = new ZipEntry(fs[i].getName());
				zos.putNextEntry(ze);
				
				byte[] buf = new byte[1024];
				int len = 0;
				while((len = is.read(buf))!=-1){
					zos.write(buf,0,len);
				}
				is.close();
			}
			zos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值