Topic: 下面那个nio教材的试验

  Print this page

1.下面那个nio教材的试验 Copy to clipboard
Posted by: alin_ass
Posted on: 2003-11-25 23:14

package io;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class CopyFile {
  FileChannel fcin;
  FileChannel fcout;
  int bufferSize;

  CopyFile(String infile, String outfile, int bufferSize) throws Exception {
    fcin = new FileInputStream(infile).getChannel();
    fcout = new FileOutputStream(outfile).getChannel();
    this.bufferSize = bufferSize;
  }

  public void copy() throws Exception {
    ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
    for (int i = 0; i < 100000; i++) {
      while (true) {
        buffer.clear();
        //正常情况下,应该是按缓冲区的大小分批把通道中的字节读入缓冲区
        int r = fcin.read(buffer);
        if (r == -1) {
          break;
        }
        buffer.flip();
        fcout.write(buffer);
      }
    }
  }

  static public void main(String args[]) {
    try {
      CopyFile cf =
        new CopyFile(
          "G:/javaProject/javastudy/src/io/infile.txt",
          "G:/javaProject/javastudy/src/io/outfile.txt",
          10000);
      long startTime = System.currentTimeMillis();
      cf.copy();
      System.out.println(System.currentTimeMillis() - startTime);
    } catch (Exception e) {
      System.out.println(System.err);
    }
  }
}
-------
在main里面做缓冲区大小改变并让他拷贝100000次文件(2000多字节),10个字节跟10000个字节都是250毫秒左右真奇怪


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923