A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© fjl_fight 中级黑马   /  2013-5-3 17:02  /  1836 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

内存映射操作文件是最快的,怎样用内存映射方式复制文件?

4 个回复

倒序浏览
谢了,但是他没有用内存映射读文件啊,我要的是用内存映射方式读写文件
回复 使用道具 举报
本帖最后由 vigiking 于 2013-5-3 19:22 编辑
  1. <div class="blockcode"><blockquote><p>package sample;</p><p>import java.io.FileInputStream;
  2. import java.io.FileOutputStream;
  3. import java.nio.ByteBuffer;
  4. import java.nio.channels.FileChannel;</p><p>public class CopyFile {
  5. public static void main(String[] args) throws Exception {
  6.   String infile = "C:\\copy.sql";
  7.   String outfile = "C:\\copy.txt";
  8.   // 获取源文件和目标文件的输入输出流
  9.   FileInputStream fin = new FileInputStream(infile);
  10.   FileOutputStream fout = new FileOutputStream(outfile);
  11.   // 获取输入输出通道
  12.   FileChannel fcin = fin.getChannel();
  13.   FileChannel fcout = fout.getChannel();
  14.   // 创建缓冲区
  15.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  16.   while (true) {
  17.    // clear方法重设缓冲区,使它可以接受读入的数据
  18.    buffer.clear();
  19.    // 从输入通道中将数据读到缓冲区
  20.    int r = fcin.read(buffer);
  21.    // read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
  22.    if (r == -1) {
  23.     break;
  24.    }
  25.    // flip方法让缓冲区可以将新读入的数据写入另一个通道
  26.    buffer.flip();
  27.    // 从输出通道中将数据写入缓冲区
  28.    fcout.write(buffer);
  29.   }
  30. }
  31. }
  32. </p><blockquote>
复制代码
回复 使用道具 举报
可以参考:http://www.iteye.com/topic/834447
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马