标签:文件的拆分和合并
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;
/*
* 文件的拆分和合并
*/
public class Test07 {
public static void main(String[] args) throws IOException {
// splitFile();
mergeFile2();
}
// 拆分文件:一个输入流、多个输出流
public static void splitFile() throws IOException {
FileInputStream fis = new FileInputStream("D:\\Java\\itany.bmp");
FileOutputStream fos = null;
byte[] buffer = new byte[1024 * 1024];// 每次读取1M
int num;
int count = 1;
while ((num = fis.read(buffer)) != -1) {
fos = new FileOutputStream("D:\\Java\\splitFiles\\itany"
+ (count++) + ".part");
fos.write(buffer, 0, num);
fos.flush();
fos.close();
}
fis.close();
System.out.println("拆分文件成功!");
}
// 合并文件:一个输出流、多个输入流
public static void mergeFile() throws IOException {
FileInputStream fis1 = new FileInputStream(
"D:\\Java\\splitFiles\\itany1.part");
FileInputStream fis2 = new FileInputStream(
"D:\\Java\\splitFiles\\itany2.part");
FileInputStream fis3 = new FileInputStream(
"D:\\Java\\splitFiles\\itany3.part");
FileOutputStream fos = new FileOutputStream(
"D:\\Java\\splitFiles\\itany.bmp");
byte[] buffer = new byte[1024 * 1024];
int num;
while ((num = fis1.read(buffer)) != -1) {
fos.write(buffer, 0, num);
}
while ((num = fis2.read(buffer)) != -1) {
fos.write(buffer, 0, num);
}
while ((num = fis3.read(buffer)) != -1) {
fos.write(buffer, 0, num);
}
fos.flush();
fos.close();
fis1.close();
fis2.close();
fis3.close();
System.out.println("合并文件成功!");
}
// SequenceInputStream 表示其他输入流的逻辑串联
public static void mergeFile2() throws IOException {
FileOutputStream fos = new FileOutputStream(
"D:\\Java\\splitFiles\\itany.bmp");
//定义一个Vector集合,保存InputStream
Vector<InputStream> v=new Vector<InputStream>();
for(int i=1;i<=3;i++){
v.add(new FileInputStream("D:\\Java\\splitFiles\\itany"+i+".part"));
}
//获取Enumeration实例
Enumeration<InputStream> e=v.elements();
//定义一个SequenceInputStream
SequenceInputStream sis=new SequenceInputStream(e);
byte[] buffer=new byte[1024];
int num;
while((num=sis.read(buffer))!=-1){
fos.write(buffer, 0, num);
}
fos.flush();
fos.close();
sis.close();
System.out.println("合并文件成功!");
}
}
标签:文件的拆分和合并
原文地址:http://blog.csdn.net/wangzi11322/article/details/44699557