Java深入---百万数据提取最大的前一百个数据

package BigData;

import java.io.*;
import java.util.PriorityQueue;
import java.util.Queue;

public class FileTest {
	public FileTest() {
	}

	public static void main(String[] args) {
		// madeData();
		sortData();
	}

	private static void sortData() {
		FileReader fr = null;
		BufferedReader br = null;
		Queue priorityQueue = new PriorityQueue(100);
		try {
			fr = new FileReader("F:/add3.txt");
			br = new BufferedReader(fr);
			int temp;
			int temp1;
			String str = null;
			long begin3 = System.currentTimeMillis();
			while ((str = br.readLine()) != null) {
				temp = Integer.valueOf(str);
				if (priorityQueue.size() < 100) {
					priorityQueue.add(temp);
				} else {
					temp1 = priorityQueue.poll();
					if (temp1 < temp) {						
						priorityQueue.offer(temp);
					}else{
						priorityQueue.offer(temp1);
					}
				}
				System.out.println("FileReader执行耗时:" + priorityQueue.toString());
			}
			br.close();
			fr.close();
			long end3 = System.currentTimeMillis();
			System.out.println("FileReader执行耗时:" + (end3 - begin3) + " 豪秒");
			System.out.println("FileReader执行耗时:" + priorityQueue.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	private static void madeData() {
		FileWriter fw = null;
		int count = 1000000;// 写文件行数
		try {
			fw = new FileWriter("F:/add3.txt");
			int temp = (int) (Math.random() * 1000000);
			long begin3 = System.currentTimeMillis();
			for (int i = 0; i < count; i++) {
				temp = (int) (Math.random() * 1000000);
				fw.write(temp + "\r\n");
			}
			fw.close();
			long end3 = System.currentTimeMillis();
			System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}
}
维护一个堆,然后向里面添加数据。。。

你可能感兴趣的:(Java)