读取文本文件内容(Java FileChannel)

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 读取文本文件内容(Java FileChannel)。
 * @author Bright Lee
 */
public class FileChannelTest {

	public static void main(String[] args) {
		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile("C:\\JavaNIO\\test.txt", "rw");
			
			FileChannel channel = file.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			
			while (true) {
				int count = channel.read(buffer);
				if (count <= -1) {
					break;
				}
				buffer.flip();
				while (buffer.hasRemaining()) {
					char ch = (char) buffer.get();
					System.out.print(ch);
				}
				buffer.compact();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (file != null) {
					file.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

运行结果:
Hello world! Java file NIO

猜你喜欢

转载自blog.csdn.net/look4liming/article/details/86359021