/**
* SequenceInputStream(合并流):对多个流进行合并 构造函数:
* public SequenceInputStream(Enumeration<? extends InputStream> e):
* 新创建的SequenceInputStream,该参数必须是生成运行时类型为 InputStream对象的 Enumeration 型参数.
* public SequenceInputStream(InputStream s1, InputStream s2):
* 通过记住这两个参数来初始化新创建的SequenceInputStream(将按顺序读取这两个参数,先读取 s1,然后读取 s2),以提供从此 SequenceInputStream
* 读取的字节。
*/
public class Demo {
public static void main(String[] args) throws IOException {
// fileMage();
// merge2();
// splitFile();
merge();
}
// 合并文件
private static void merge() throws FileNotFoundException, IOException {
ArrayList<FileInputStream> al = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
al.add(new FileInputStream("test" + i + ".part"));
}
final java.util.Iterator<FileInputStream> it = al.iterator();
// Enumeration是接口,要复实现其接口中的方法
Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {
@Override
public boolean hasMoreElements() {
// 是否还有下一个元素
return it.hasNext();
}
@Override
public FileInputStream nextElement() {
// 返回下一个元素
return it.next();
}
};
// 创建合并流
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream("test_copy.wmv");
byte[] buf = new byte[1024 * 1024 * 10];
int len = 0;
while ((len = sis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.close();
sis.close();
}
// 切割文件
private static void splitFile() throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("test.wmv");
FileOutputStream fos = null;
int count = 1;
int len = 0;
byte[] byArray = new byte[1024 * 1024 * 10];
while ((len = fis.read(byArray)) != -1) {
fos = new FileOutputStream("test" + (count++) + ".part");
fos.write(byArray, 0, byArray.length);
fos.close();
}
fis.close();
}
private static void merge2() throws FileNotFoundException, IOException {
// 创建一个FileInputStream集合
Vector<FileInputStream> v = new Vector<>();
v.add(new FileInputStream("test1.txt"));
v.add(new FileInputStream("test2.txt"));
v.add(new FileInputStream("test3.txt"));
v.add(new FileInputStream("test4.txt"));
// 将集合元素转化为Enumeration(合并流构造函数需要)
Enumeration<FileInputStream> en = v.elements();
// 创建合并流
SequenceInputStream sis = new SequenceInputStream(en);
// 创建一个输出流,用于读取数据
FileOutputStream fos = new FileOutputStream("test1234.txt");
int len = 0;
byte[] byArray = new byte[1024];
while ((len = sis.read(byArray, 0, byArray.length)) != -1) {
fos.write(byArray, 0, len);
fos.write("\n".getBytes());
}
}
private static void mergeFile() throws FileNotFoundException, IOException {
// 构造一个"合并流"
SequenceInputStream sis = new SequenceInputStream(new FileInputStream(
"test1.txt"), new FileInputStream("test2.txt"));
// 创建一个输出流,用于读取数据
FileOutputStream fos = new FileOutputStream("test1_test2.txt");
int len = 0;
byte[] byArray = new byte[1024];
while ((len = sis.read(byArray, 0, byArray.length)) != -1) {
fos.write(byArray, 0, len);
fos.write("\n".getBytes());
}
}
} |
|