/**
* 日志类,将用户的操作信息写入日志文件中
*/
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();
}
}