您的位置:首页 > 其它

将一个文件分割(1M)和合并

2017-09-20 17:27 183 查看
package com.zk919;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

/**
* 练习:
* 将一个文件分割(1M)和合并,合并的文件与源文件大小一致
*/
public class Demo7 {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//cutFile();   分割文件
//conFile();	合并文件
}

public static void conFile() throws FileNotFoundException, IOException {
File dir = new File("e:\\123");  //要合并的文件的路径
File[] files = dir.listFiles();
Vector<FileInputStream> vector = new Vector<FileInputStream>();
for (int i=0; i<files.length; i++) {
if (files[i].getName().endsWith("rar")) {  //取出末尾为rar的文件
vector.add(new FileInputStream(files[i]));  //把要合成的加入到vector集合中
}
}
Enumeration<FileInputStream> e = vector.elements();

SequenceInputStream sq = new SequenceInputStream(e);

FileOutputStream fos = new FileOutputStream("e:\\666.rar");
byte[] buf = new byte[1024];
int length = 0;
while ((length=sq.read(buf)) != -1) {
fos.write(buf, 0, length);
}
fos.close();
sq.close();
}

public static void cutFile() throws FileNotFoundException, IOException {
int i = 1;
File inFile = new File("e:\\plsqldeveloper9.0.rar");   //要分割的文件的路径
//		File outFile = new File("e:\\"+i+".rar");
FileInputStream fis = new FileInputStream(inFile);
//		FileOutputStream fos = new FileOutputStream(outFile);
byte[] buf = new byte[1024*1024];
int length = 0;
while ((length=fis.read(buf)) != -1) {		//分割文件,一个1M,写入文件
FileOutputStream fos = new FileOutputStream("e:\\"+i+".rar");
fos.write(buf, 0, length);
i++;
fos.close();
}
fis.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: