文件拆分

找到一个大于100k的文件,按照100k为单位,拆分成多个子文件,并且以编号作为文件名结束。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
  
public class TestStream {
  
    public static void main(String[] args) {
     int eachSize = 100 * 1024;//100字节
     File f = new File("E:/eclipse/eclipse.exe");
     splitFile(f, eachSize);
    }
    //拆分的思路,先把源文件的所有内容读取到内存中,然后从内存中挨个分到子文件里
    public static void splitFile(File f, int eachSize){
     if (f.length() == 0){
      throw new RuntimeException("文件长度等于0,不可拆分");//如果文件长度为0,则抛出一个运行时异常
     }    
     byte fileCount[] = new byte[(int)f.length()];     
     try{//先将文件读入到数组中
      FileInputStream fs = new FileInputStream(f); 
      fs.read(fileCount);
      fs.close();
     }catch(IOException e){
      e.printStackTrace();
     }
     int fileNumber;//计算需要被拆分为多少子文件
     if (fileCount.length % eachSize == 0){
      fileNumber = (int)fileCount.length / eachSize;
     }
     else{
      fileNumber = (int)fileCount.length / eachSize + 1;
     }
     for (int i = 0; i < fileCount.length; i++) {
   String eachFileName = f.getName() + "-" + i;
   File eachFile = new File(f.getParent(), eachFileName);
   byte eachContent[];
   // 从源文件的内容里,复制部分数据到子文件
            // 除开最后一个文件,其他文件大小都是100k
            // 最后一个文件的大小是剩余的
   if (fileNumber - 1 != i){// 不是最后一个
    eachContent = Arrays.copyOfRange(fileCount, i * eachSize, (i + 1) * eachSize);
   }
   else{// 最后一个
    eachContent = Arrays.copyOfRange(fileCount, i * eachSize, fileCount.length);
   }
   try{ // 写出去
    FileOutputStream fs2 = new FileOutputStream(eachFile);
    fs2.write(eachContent);
    fs2.close();
    System.out.printf("输出子文件%s,其大小是%d字节%n", eachFile.getAbsoluteFile(), eachFile.length());
   }catch(IOException e){
    e.printStackTrace();
   }
  }
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值