import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class GetChannel {
static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
FileChannel channel = new FileOutputStream("data.txt").getChannel();
channel.write(ByteBuffer.wrap("Some text".getBytes()));
channel.close();
channel = new RandomAccessFile("data.txt", "rw").getChannel();
channel.position(channel.size());// 移动到文件结尾
channel.write(ByteBuffer.wrap(" Some more".getBytes()));
channel.close();
channel = new FileInputStream("data.txt").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
channel.read(buffer);
buffer.flip();// 反转此通道
while (buffer.hasRemaining()) {
System.out.println((char) buffer.get());
}
}
}
JAVA 新I/O 之 FileChannel,ByteBuffer
最新推荐文章于 2024-07-15 15:40:07 发布