黑马程序员技术交流社区
标题:
io切割文件
[打印本页]
作者:
BlueSun
时间:
2015-8-22 16:17
标题:
io切割文件
缓冲区定义1M,每次切割的小文件为1M。如果我要把一个500M的文件切割成5份,每份100M,程序怎么改。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class SplitFileDemo{
private static final int SIZE = 1024*1024;
public static void main(String[] args) throws IOException{
File file = new File("0.mp3" );
splitFile(file);
}
public static void splitFile(File file) throws IOException {
//用读取流关联源文件
FileInputStream fis = new FileInputStream(file);
//定义一个1M的缓冲区
byte[] buf = new byte[SIZE];
//创建目的
FileOutputStream fos = null;
int len = 0;
int count = 1;
//切割文件时,必须记录住被切割文件的名称,以及切割出来碎片文件的个数,以方便于合并。
//这个信息为了进行描述,使用键值对的方式,用到了properties对象。
Properties prop = new Properties();
File dir = new File("c:\\partFiles" );
if(!dir.exists())
dir.mkdirs();
while((len = fis.read(buf)) != -1){
fos = new FileOutputStream(new File(dir,(count++) + ".part"));
fos.write(buf,0,len);
fos.close();
}
//将被切割文件的信息保存到prop集合中
prop.setProperty( "partcount",count + "" );
prop.setProperty( "filename",file.getName());
fos = new FileOutputStream(new File(dir,count + ".properties" ));
//将prop集合中的数据存储到文件中
prop.store(fos, "save file info");
fis.close();
fos.close();
}
}
复制代码
作者:
张业涛
时间:
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