写入文件
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream("abc.txt");
// 得到对应的通道
FileChannel channel = fileOutputStream.getChannel();
// 提供一个缓冲区并存入数据
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.put("abc".getBytes());
// 重置到初始位置
byteBuffer.flip();
// 写入通道中
channel.write(byteBuffer);
// 关闭
channel.close();
读取文件
// 创建输入流
File file = new File("abc.txt");
FileInputStream fileInputStream = new FileInputStream(file);
// 得到对应的通道
FileChannel channel = fileInputStream.getChannel();
// 从通道中读取数据并存到缓冲区中
ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
channel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
// 关闭
channel.close();
复制文件
// 创建输入输出流
FileInputStream fileInputStream = new FileInputStream("abc.txt");
FileOutputStream fileOutputStream = new FileOutputStream("copy.txt");
// 得到对应的通道
FileChannel sourceChannel = fileInputStream.getChannel();
FileChannel descChannel = fileOutputStream.getChannel();
// 复制
sourceChannel.transferTo(0, sourceChannel.size(), descChannel);
// 关闭
sourceChannel.close();
descChannel.close();