很多网站在上传单个文件的时候,都有大小限制,比如说单个文件不能超过5M,而我们要上传的文档可能有20多M,经常我们只能用压缩软件将这个大文件分割压缩成好几个分卷上传上去。当别人把这些分卷都下载下来后,用解压软件,就可以合并成原始的大文件了。今天,来讲述一下,javaIO中如何切割和合并一个文件。
现在我有一个音乐文件 1.mp3,大小6.58M,而分割后的文件大小不超过1M,所以要分割成7个小文件,命名为
1.part 、2.part.....7.part。
1、文件的切割:将一个大文件按照一定的大小切割成多个小文件
①为要切割的文件建立一个FileInputStream,
②建立一个字节缓冲区byte[] buf
③从FileInputStream中,将数据循环读取到buf中,记录每次读写的大小
④循环将读取的数据写到新建的FileOutputStream中,
⑤关闭相关流
2、文件的合并:将多个被切割的文件合并起来
①为要合并的多个文件,分别创建FileInputStream,
②将这过个FileInputStream添加到Enumeration中
③以Enumeration为参数,构造一个SequenceInputStream对象,这个
SequenceInputStream对象就将多个输入流合并成一个了
④为合并后的文件建立一个从FileOutputStream对象
⑤将从从SequenceInputStream中读取数据写到FileOutputStream中
⑥关闭相关流
3、文件分割和合并程序的代码:
import java.io.*;
import java.util.*;
class SplitFile
{
public static void main(String[] args) throws IOException
{
splitFile();
merge();
}
//1文件的切割:
public static void splitFile() throws IOException
{
FileInputStream fis=new FileInputStream("D:\\1.mp3");
FileOutputStream fos=null;
byte[] buf=new byte[1024*1024];
int len=0;
int count=1;
//将文件1.mp3按照1M大小切割
while((len=fis.read(buf))!=-1)
{
fos=new FileOutputStream("D:\\zsw\\"+(count++)+".part");
fos.write(buf,0,len);
fos.close();
}
fis.close();
}
//2文件的合并
public static void merge() throws IOException
{
ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();
//根据合并的文件数量确定i的值,并注意文件的先后顺序
for(int x=1;x<=7;x++)
{
al.add(new FileInputStream("D:\\zsw\\"+x+".part"));
}
final Iterator<FileInputStream>it=al.iterator();
Enumeration<FileInputStream>en=new Enumeration<FileInputStream>()
{
public boolean hasMoreElements()
{
return it.hasNext();
}
public FileInputStream nextElement()
{
return it.next();
}
};
//多个输入流合并成一个输入流sis
SequenceInputStream sis=new SequenceInputStream(en);
FileOutputStream fos=new FileOutputStream("D:\\zsw\\1.mp3");
byte[] buf=new byte[1024];
int len=0;
while((len=sis.read(buf))!=-1)
{
fos.write(buf,0,len);
}
fos.close();
sis.close();
}