Java多线程生成测试文件

import java.io.File;
import java.io.FileInputStream;


import java.io.FileOutputStream;

import org.boris.expr.Expr;
import org.boris.expr.ExprEvaluatable;
import org.boris.expr.parser.ExprParser;
import org.boris.expr.util.Exprs;
import org.boris.expr.util.SimpleEvaluationContext;
//使用到了expr
//http://nchc.dl.sourceforge.net/project/expr4j/expr4j/0.0.1/expr4j-0.0.1.zip
//多线程生成测试文件
public class TestData {

	public static void main(String[] args) {

		if (args.length != 3) {
			System.out.println("Usage: inputFile size(M)/Expr threads");
			//java -jar testData.jar data5g\明辉购房笔记.TXT 1024*5 15
			return;
		}
		File inputFile = new File(args[0]);
		if(!inputFile.exists())
		{
			System.out.println("源文件不存在");
		
			return;		
		}	
		Expr expr = null;
		try {
			 expr = ExprParser.parse(args[1]);
			Exprs.toUpperCase(expr);		
			if (expr instanceof ExprEvaluatable) {
				expr = ((ExprEvaluatable) expr).evaluate(new SimpleEvaluationContext());
			}
			System.out.println("表达式计算结果:"+expr);
		} catch (Exception e) {
			e.printStackTrace();
			return ;
		}
				
		long size = (long) (1024  * Double.parseDouble(expr.toString()));// m
		long fileSize = inputFile.length() / 1024;
		int threads = Integer.parseInt(args[2]);

		long filecount = size / fileSize;
		long parts = filecount / threads;// 每个线程生成的文件数目
		Thread[] mythreads=new MyThread[threads];
		for (int i = 0; i < threads; i++) {
			mythreads[i] = new MyThread(i+1, i * parts, (i + 1) * parts,inputFile);
			mythreads[i].start();
		}
		while(true)
		{
			boolean isAllFinish=true;
			for (Thread thread : mythreads) {
				if(thread.isAlive())
				{
					isAllFinish=false;
				}
			}
			if(isAllFinish)
			{
				System.out.println("全部执行完成");
				break;
			}
		}

	}

	static class MyThread extends Thread {

		private int id;
		private long startIndex;
		private long endIndex;
		private File inputFile;
		//private boolean isFinish=false;

		public MyThread(){}
		
		public MyThread(int i, long l, long m, File inputFile) {
			this.id = i;
			this.startIndex = l;
			this.endIndex = m;
			this.inputFile = inputFile;
		}

		@Override
		public void run() {

			try {
				System.out.println("线程"+id+"启动");
				for (long i = startIndex; i < endIndex; i++) {
					copyFile(inputFile, new File(inputFile.getParent(), (i+1)+ inputFile.getName()));
				}
				//isFinish=true;
				System.out.println("线程"+id+"执行完成");
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.run();
		}

	}

	private static void copyFile(File inputfile, File outputFile)
			throws Exception {

		FileInputStream fileInputStream = new FileInputStream(inputfile);
		FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fileInputStream.read(buffer)) != -1) {
			fileOutputStream.write(buffer, 0, len);
		}
		fileOutputStream.flush();
		fileOutputStream.close();
		fileInputStream.close();

	}
}

你可能感兴趣的:(Java多线程生成测试文件)