Java NIO之用Channel和MappedByteBuffer高效快速复制大文件 ...

NIO的应用,复制大文件,超爽,简单高效

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class Demo05 {
public static void main(String[] args) throws Exception {
    FileChannel inChannel=new RandomAccessFile("f:\\01.wmv", "r").getChannel();
    FileChannel outChannel=new RandomAccessFile("f:\\02.wmv", "rw").getChannel();
    
    MappedByteBuffer map=inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
    
    outChannel.write(map);
    outChannel.close();
    inChannel.close();
    System.out.println("复制完毕");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用 `MappedByteBuffer` 来实现随机读取文件。`MappedByteBuffer` 是 `ByteBuffer` 的子类,它通过将文件映射到内存中的字节缓冲区来实现对文件的随机访问。 下面是一个使用 `MappedByteBuffer` 随机读取文件的示例代码: ```java import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class FileRandomAccess { public static void main(String[] args) throws Exception { // 打开文件 RandomAccessFile file = new RandomAccessFile("path/to/file", "r"); // 获取文件通道 FileChannel channel = file.getChannel(); // 将文件映射到内存中 MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); // 随机读取文件内容 byte[] data = new byte[buffer.remaining()]; buffer.get(data); // 关闭文件通道和文件 channel.close(); file.close(); // 处理读取到的数据 System.out.println(new String(data)); } } ``` 上述代码中,首先通过 `RandomAccessFile` 打开文件,并获取其通道。然后使用 `FileChannel` 的 `map` 方法将文件映射到内存中的 `MappedByteBuffer` 对象。通过 `MappedByteBuffer` 对象可以直接读取文件内容,而无需进行显式的读取操作。最后,记得关闭文件通道和文件。 请注意替换示例代码中的 `"path/to/file"` 为实际的文件路径。另外,为了简化示例代码,这里将整个文件映射到内存中,你也可以根据需要仅映射文件的部分内容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值