大文件切割

大日志文件切割


场景:在window上编辑器查看过大的日志看不了,也懒得找其他编辑器或者工具,写了个代码,把日志文件切分成n个小文件

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BigFile implements Runnable{
	
	private char[] fileCharBuf = null;
	private int readLent = 0;
	private int index = 1;
	
	private static final String FILE_NAME = "E:\\bak\\"; //小日志备份目录
	private static final String LOG_PATH = "E:\\log.log"; //日志文件目录
	private static final Charset  CHARSET_UTF8= Charset.forName("UTF-8"); //文件字符编码
	private static final int  FILE_SIZE = 1024 * 1024 * 30; //30MB
	
	BigFile(char[] fileCharBuf,int readLent,int index){
		this.fileCharBuf = fileCharBuf;
		this.readLent = readLent;
		this.index = index;
	}
	
	public static void main(String[] args) throws Exception {
		ExecutorService executorService = Executors.newFixedThreadPool(5);
		
		File srcFile = new File(LOG_PATH); 
		
		//新建目录
		File targetDir = new File(FILE_NAME);
		if(!targetDir.exists()) {
			targetDir.mkdirs();
		}
		
		long fileSize =  srcFile.length();
		char[] chbuf = new char[FILE_SIZE];
		int fileNum = (int)(fileSize / chbuf.length);
		BufferedReader readerBuffer = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile),CHARSET_UTF8.name()));
		int ret = readerBuffer.read(chbuf);
		
		int index = 1;
		for(int i = 0; i < fileNum && ret != -1; i++) {
			chbuf = new char[FILE_SIZE];
			executorService.submit(new BigFile(chbuf,ret,index++));
			ret = readerBuffer.read(chbuf);
		}
		readerBuffer.close();
		executorService.shutdown();
		
		if(ret != -1) {
			BufferedWriter writerBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FILE_NAME + "log_" + (index) + ".log")));
			writerBuff.write(chbuf, 0, ret);
			writerBuff.close();
		}
	}

	@Override
	public void run() {
		try {
			BufferedWriter writerBuff = null;
			writerBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FILE_NAME + "log_" + (index) + ".log")));
			writerBuff.write(fileCharBuf, 0,readLent);
			writerBuff.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值