用java.NIO包的类。遇到问题。求帮忙!

DONFANS 发布于 2012/11/12 14:09
阅读 403
收藏 0

package cn.IO;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;


public class FileSplitAndSequence {

 /**
  * 练习用NIO包的类切割文件
  */
 public static void main(String[] args) {

  String fileName="D:\\Downloads\\WINPE.rar";
  File f=new File(fileName);
  FileSplit fs=new FileSplit(fileName,(int) f.length());
  File destDir=new File("D:\\Downloads");
  
  fs.cut(destDir);
 }

 }

class FileSplit {
 public static ArrayList<File> cutFiles = new ArrayList<File>();
 private String fileName;
 private int size;

 public FileSplit(String fileName, int size) {
  this.fileName = fileName;
  this.size = size ;
 }
 
 public void cut(File destDir) {
  File fileIn = new File(fileName);
  int fileCnt = this.countFileSize(size); // 一般文件2G内足够了
  if(fileCnt==-1){
   return;
  }  

  FileChannel fcIn = null;
  RandomAccessFile rafIn = null;
  RandomAccessFile rafOut = null;
  FileChannel fcOut = null;

  try {
   int eachSize=size/fileCnt;
   rafIn = new RandomAccessFile(fileIn, "r");
   fcIn = rafIn.getChannel();
   for (int i = 0; i < fileCnt; i++) {
    //System.out.println(fileCnt);
    String part="(part" + (i + 1) + ")";
    String filePartName =fileIn.getName();
    if(fileCnt!=1){
     filePartName=part+filePartName;
    }
    File filePart = new File(destDir.getAbsolutePath()+"/"+filePartName);
    if(!filePart.exists()){
     filePart.createNewFile();
    }
    cutFiles.add(filePart);

    MappedByteBuffer mbIn = fcIn.map(FileChannel.MapMode.READ_ONLY,
      i * eachSize, eachSize);

    rafOut = new RandomAccessFile(filePart, "rw");
    fcOut = rafOut.getChannel();
    MappedByteBuffer mbOut = fcOut.map(
      FileChannel.MapMode.READ_WRITE, 0, eachSize);
    for (int j=0; j <eachSize; j++) {
     byte b=mbIn.get(j+i*eachSize);//这里报异常??
     mbOut.put(j, b);
    }
    
   }
   System.out.println("分割成功");
  } catch (Exception e) {
   throw new RuntimeException(e);
  } finally {
   try {
    if (rafIn != null) {
     rafIn.close();
    }
    if (fcIn != null) {
     fcIn.close();
    }
    if (rafOut != null) {
     rafOut.close();
    }
    if (fcOut != null) {
     fcOut.close();
    }
   } catch (IOException e) {
    throw new RuntimeException(e);
   }
  }

 }
 //根据大小确定切割个数
 private int countFileSize(int i){
  int k=10<<10<<10; //10M范围内
  int j=100<<10<<10;//100M
  int h=1<<10<<10<<10;//1G
  if(i>0&&i<=k){
   return 1;
  }else if(i>k&&i<=j){
   return 5;
  }else if(i>j&&i<=h){
   return 10;
  }else if(i>h&&i<=2*h){
   return 20;
  }
  
  return -1;
 }
}

Eclipse说  byte b=mbIn.get(j+i*eachSize); 这里有异常,

可是我感觉没错啊??

求达人帮忙看下。。 怎么解决呢?

 

 

加载中
0
Gaischen
Gaischen
Throws:
IndexOutOfBoundsException - If index is negative or not smaller than the buffer's 

limit

是报这个错么,是得话 就看看 buffer的指针位置和index的位置

DONFANS
DONFANS
恩。找到了。脑子短路了
0
杀_猪_的
异常贴出来啊。。。
返回顶部
顶部