package com.bjorktech.cayman.idea.corejava.io.nio.fileio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.Charset;

public class FileLockDemo {
	public static void readFile() {
		long timeBegin = System.currentTimeMillis();
		try (RandomAccessFile aFile = new RandomAccessFile("src/io.txt", "rw")) {
			FileChannel fileChannel = aFile.getChannel();
			ByteBuffer buf = ByteBuffer.allocate(1024);
			Charset charset = Charset.forName("UTF-8");

			int position = 0;
			while (true) {
				// 文件锁，锁一段区域，shard为true表示共享锁
				FileLock fileLock = fileChannel.lock(position, 1024, true);
				int bytesRead = fileChannel.read(buf);
				fileLock.release();
				if (-1 == bytesRead)
					break;
				position = position + bytesRead;
				buf.flip();
				//将ByteBuffer转化为CharBuffer
				System.out.println(charset.decode(buf));
				buf.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		long timeEnd = System.currentTimeMillis();
		System.out.println("Read time: " + (timeEnd - timeBegin) + "ms");
	}
}
