Java 新I/O 通道和缓冲器

本文详细介绍了Java NIO中的文件通道操作,包括如何创建、写入、追加和读取文件,以及如何使用ByteBuffer进行高效的数据传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package io;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
/*
 * 三种类型的流用以产生可写的,可读的,可读可写的通道。
 * getChannel()将会产生一个FileChannel通道,可以向他传送用于读写的ByteBuffer,并且可以锁定文件的某些区域用于独占式访问。
 * 将字节放于ByteBuffer中的方法用put方法,也可以用wrap方法将以存在的字节数组包装到ByteBuffer中。一旦如此,就不会复制底层的数组
 * 而是把它作为所产生ByteBuffer的存储器,称之为数组支持的ByteBuffer。
 * 一旦调用read()来告知FileChannel向ByteBuffer存储字节,就必须调用缓冲器上的flip(),让他做好别人读取字节的准备。*/
public class GetChannel {
  private static final int BSIZE = 1024;
  @SuppressWarnings("resource")
public static void main(String[] args) throws Exception {
    // Write a file:
    @SuppressWarnings("resource")
	FileChannel fc = new FileOutputStream("data.txt").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();
    // Add to the end of the file:
    fc = new RandomAccessFile("data.txt", "rw").getChannel();
    fc.position(fc.size()); // Move to the end
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();
    // Read the file:
    fc = new FileInputStream("data.txt").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    fc.read(buff);
    buff.flip();
    while(buff.hasRemaining())
      System.out.print((char)buff.get());
  }
} /* Output:
Some text Some more
*///:~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值