1 24 25 package com.mckoi.util; 26 27 import java.io.*; 28 29 35 36 public class LogWriter extends Writer { 37 38 41 private final File log_file; 42 43 46 private final long max_size; 47 48 51 private final int archive_count; 52 53 56 private long log_file_size; 57 58 61 private Writer out; 62 63 68 public LogWriter(File base_name, long max_size, int archive_count) 69 throws IOException { 70 71 if (archive_count < 1) { 72 throw new Error ("'archive_count' must be 1 or greater."); 73 } 74 75 this.log_file = base_name; 76 this.max_size = max_size; 77 this.archive_count = archive_count; 78 79 if (base_name.exists()) { 81 log_file_size = base_name.length(); 82 } 83 else { 84 log_file_size = 0; 85 } 86 out = new BufferedWriter(new FileWriter(base_name.getPath(), true)); 87 88 } 89 90 94 private void checkLogSize() throws IOException { 95 if (log_file_size > max_size) { 96 out.flush(); 98 out.close(); 100 out = null; 101 File top = new File(log_file.getPath() + "." + archive_count); 103 top.delete(); 104 for (int i = archive_count - 1; i > 0; --i) { 106 File source = new File(log_file.getPath() + "." + i); 107 File dest = new File(log_file.getPath() + "." + (i + 1)); 108 source.renameTo(dest); 109 } 110 log_file.renameTo(new File(log_file.getPath() + ".1")); 111 112 out = new BufferedWriter(new FileWriter(log_file.getPath(), true)); 114 log_file_size = 0; 115 } 116 } 117 118 120 public synchronized void write(int c) throws IOException { 121 out.write(c); 122 ++log_file_size; 123 } 124 125 public synchronized void write(char cbuf[], int off, int len) 126 throws IOException { 127 out.write(cbuf, off, len); 128 log_file_size += len; 129 } 130 131 public synchronized void write(String str, int off, int len) 132 throws IOException { 133 out.write(str, off, len); 134 log_file_size += len; 135 } 136 137 public synchronized void flush() throws IOException { 138 out.flush(); 139 checkLogSize(); 140 } 141 142 public synchronized void close() throws IOException { 143 out.flush(); 144 out.close(); 145 } 146 147 } 148 | Popular Tags |