Java NIO FileChannel读

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/88233746
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileTest {
	public static void main(String[] args) {
		try {
			new FileTest();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public FileTest() throws Exception {
		String path = "D:/code/file.txt";
		RandomAccessFile raf = new RandomAccessFile(path, "rw");
		FileChannel fc = raf.getChannel();
		System.out.println("文件总长度:" + fc.size());

		System.out.println("文件全部内容:");
		printer(path);

		final int capacity = 3;
		ByteBuffer buffer = ByteBuffer.allocate(capacity);

		int count = 0;
		while (true) {
			System.out.println("=============");
			System.out.println("从此位置开始读:" + fc.position());

			buffer.clear();

			count = fc.read(buffer);
			if (count == -1) {
				break;
			}

			System.out.println("读取的数据:" + new String(buffer.array(), 0, count));
		}
	}

	// 打印path指向的文件中的内容。
	private void printer(String path) throws Exception {
		InputStream is = new FileInputStream(path);
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String s = null;
		while (true) {
			s = br.readLine();
			if (s != null)
				System.out.println(s);
			else
				break;
		}

		br.close();
		is.close();
	}
}

程序运行输出:

文件总长度:10
文件全部内容:
0123456789
=============
从此位置开始读:0
读取的数据:012
=============
从此位置开始读:3
读取的数据:345
=============
从此位置开始读:6
读取的数据:678
=============
从此位置开始读:9
读取的数据:9
=============
从此位置开始读:10

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/88233746