读取文件 (NIO 四)

经典的I/O方式

这个示例展示了我们如何使用旧的I/O库api读取文本文件。它使用BufferedReader对象进行读取。另一种方法是使用InputStream实现。

public class WithoutNIOExample {
	public static void main(String[] args) {
		String sCurrentLine = null;
		try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

NIO方式

  • 读取小文件

直接分配与文件大小一致的缓存区大小

public class ReadFileWithFileSizeBuffer {
	public static void main(String args[]) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
		FileChannel inChannel = aFile.getChannel();
		int fileSize = (int) inChannel.size();
		ByteBuffer buffer = ByteBuffer.allocate(fileSize);
		inChannel.read(buffer);

		buffer.flip();
		for (int i = 0; i < fileSize; i++) {
			System.out.println(buffer.get());
		}
		inChannel.close();
		aFile.close();
	}
}
  • 读取大文件

以固定大小缓冲区的块读取大文件

public class ReadFileWithFixedSizeBuffer {
	public static void main(String[] args) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
		FileChannel inChannel = aFile.getChannel();
		System.out.println(inChannel.size());
		// 1K
		int times = 0;
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (inChannel.read(buffer) > 0) {
			buffer.flip();
			while (buffer.hasRemaining()) {
				buffer.get();
				times++;
			}
			buffer.clear();
		}
		inChannel.close();
		aFile.close();
		System.out.println(times);
		System.out.println("finish");
	}
}
  • 文件内存映射

更快的文件操作方式

public class ReadFileWithMappedByteBuffer {
	public static void main(String[] args) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
		FileChannel inChannel = aFile.getChannel();
		System.out.println(inChannel.size());
		MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
		int times = 0;
		for (int i = 0; i < buffer.limit(); i++) {
			buffer.get();
			times++;
		}
		inChannel.close();
		aFile.close();
		System.out.println(times);
		System.out.println("finish");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值