/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.file;

import java.io.File;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author 田平 create 2017年9月3日上午8:41:19
 */
@Getter
@Setter
@ToString
public class Range implements Serializable {

	private static final long serialVersionUID = 1L;
	private long start;
	private long length;

	public Range() {
	}

	public Range(int start, int length) {
		this.start = start;
		this.length = length;
	}

	public static void main(String[] args) throws Exception {
		String url = "C:\\Users\\Administrator\\Desktop\\start2.txt";
		File file = new File(url);
		RandomAccessFile raf = new RandomAccessFile(file, "r");
		List<Range> ranges = new ArrayList<Range>();
		long section = raf.length() / 4;
		sharding(ranges, raf, 0, section);
		for (Range range : ranges) {
			System.out.println(range);
		}
	}

	public static void sharding(List<Range> ranges, RandomAccessFile raf, long position, long section) throws Exception {
		if (position > raf.length() - 1) {
			return;
		}
		Range range = new Range();
		range.start = position;

		long endPosition = position + section;
		if (endPosition >= raf.length() - 1) {
			range.length = raf.length() - position;
			ranges.add(range);
			return;
		}

		raf.seek(endPosition);
		int tmp = raf.read();
		while (!checkLineChar(tmp)) {
			endPosition++;
			if (endPosition >= raf.length() - 1) {
				endPosition = raf.length() - 1;
				break;
			}
			raf.seek(endPosition);
			tmp = raf.read();
		}
		int tmp2 = raf.read();
		if (tmp2 != -1 && checkLineChar(tmp2)) {
			endPosition++;
		}
		range.length = endPosition - position;
		ranges.add(range);
		sharding(ranges, raf, endPosition + 1, section);
	}

	public static boolean checkLineChar(int data) {
		return data == 10 || data == 13 ? true : false;
	}

	public static boolean checkLineChar(char data) {
		return data == '\n' || data == '\r' ? true : false;
	}

}
