Java 拷贝文档中的内容到另一文档中

由于log4j自带的文件分裂功能无法使用,故在代码内部实现当log文件大于一定数值时拷贝并清空

		String filename = System.getProperty("catalina.base") +"/logs/tomcat8-stdout.log";
		LOG.info("filename="+filename);
		File logfile = new File(filename);
		long lenth = logfile.length();
		LOG.info("lenth="+lenth);
		long MaxLengh = 20*1024*1024;
		if(logfile.length()>MaxLengh) { //判断log文件是否大于20M
	        //原始文档路径
	        String old = System.getProperty("catalina.base") +"/logs/tomcat8-stdout.log";
	        //新文档路径
	        String newPath = System.getProperty("catalina.base") +"/logs/tomcat8-stdout_copy.log";
	        //将原始文档通过输入流读入内存
	        FileInputStream fis = new FileInputStream(new File(old));
	        BufferedInputStream bis = new BufferedInputStream(fis);
	        InputStreamReader isr = new InputStreamReader(bis);
	        BufferedReader br = new BufferedReader(isr);
	        String temp;
	        //通过输出流将内存中的数据写出到新的文档
	        FileOutputStream fos = new FileOutputStream(new File(newPath),false);//设置为false表示每次执行不累加内容到newpath,true表示累加内容到newpath
	        BufferedOutputStream bw = new BufferedOutputStream(fos);
	        PrintWriter pw = new PrintWriter(bw);
	        while((temp= br.readLine())!=null){
	            pw.println(temp);
	        }
	        if(pw!=null){
	            pw.close();
	        }
			FileWriter fw= new FileWriter(logfile);
			fw.write("");
		    fw.flush();    
		    fw.close(); 
			LOG.info("delete" + logfile);

		}

猜你喜欢

转载自blog.csdn.net/k_prince/article/details/80773584
今日推荐