黑马程序员技术交流社区

标题: io切割文件 [打印本页]

作者: BlueSun    时间: 2015-8-22 16:17
标题: io切割文件
缓冲区定义1M,每次切割的小文件为1M。如果我要把一个500M的文件切割成5份,每份100M,程序怎么改。
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.Properties;

  6. public class SplitFileDemo{

  7.        private static final int SIZE = 1024*1024;
  8.       
  9.        public static void main(String[] args) throws IOException{
  10.             File file = new File("0.mp3" );
  11.             splitFile(file);
  12.       }

  13.        public static void splitFile(File file) throws IOException {
  14.              //用读取流关联源文件
  15.             FileInputStream fis = new FileInputStream(file);

  16.              //定义一个1M的缓冲区
  17.              byte[] buf = new byte[SIZE];
  18.       
  19.              //创建目的
  20.             FileOutputStream fos = null;
  21.             
  22.              int len = 0;
  23.              int count = 1;

  24.              //切割文件时,必须记录住被切割文件的名称,以及切割出来碎片文件的个数,以方便于合并。
  25.              //这个信息为了进行描述,使用键值对的方式,用到了properties对象。

  26.             Properties prop = new Properties();

  27.             File dir = new File("c:\\partFiles" );
  28.              if(!dir.exists())
  29.                   dir.mkdirs();

  30.              while((len = fis.read(buf)) != -1){
  31.                   fos = new FileOutputStream(new File(dir,(count++) + ".part"));
  32.                   fos.write(buf,0,len);
  33.                   fos.close();
  34.             }
  35.             
  36.              //将被切割文件的信息保存到prop集合中
  37.             prop.setProperty( "partcount",count + "" );
  38.             prop.setProperty( "filename",file.getName());

  39.             fos = new FileOutputStream(new File(dir,count + ".properties" ));
  40.             
  41.              //将prop集合中的数据存储到文件中
  42.             prop.store(fos, "save file info");

  43.             fis.close();
  44.             fos.close();
  45.       }
  46. }
复制代码

作者: 张业涛    时间: 2015-8-22 20:14
你那个size不是你定义每次copy的大小么,改那个size不就好了
作者: BlueSun    时间: 2015-8-22 20:18
张业涛 发表于 2015-8-22 20:14
你那个size不是你定义每次copy的大小么,改那个size不就好了

不行吧,size定义的是缓冲区, byte[] buf = new byte[SIZE];
缓冲区不能定义太大的范围吧
作者: 张业涛    时间: 2015-8-22 20:25
理论上你定义多少都无所谓,而实际上你电脑能拷多块呢




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2