【Knowledge】知識問答サーバー(ログ操作類)

1909 ワード

/**
 *  , 
 */
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();
		}
	}