SequenceInputStream此对象实现了将多个流转化成一个流。此对像接收的是Enumeration对象,那么如何获取Enumeration对象呢?我们通过查找api,collections类中的enumeration方法返回的就是Enumeration对象,我们将多个流对象封装进集合中,最终传进SequenceInputStream对象中,通过操作SequenceInputStream对象来实现复制
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
public class IoDemo {
public static void main(String[] args) throws IOException {
ArrayList<InputStream> al = new ArrayList();
al.add(new FileInputStream("e:/1.txt"));
al.add(new FileInputStream("e:/2.txt"));
al.add(new FileInputStream("e:/3.txt"));
// 获取Enumeration对象
Enumeration<InputStream> en = Collections.enumeration(al);
SequenceInputStream sq = new SequenceInputStream(en);
FileOutputStream fo = new FileOutputStream("e:/lishuai.txt");
int len = 0;
byte[] b = new byte[1024];
while ((sq.read(b)) != -1) {
fo.write(b, 0, len);
}
sq.close();
fo.close();
}
}
对象的持久保存,我们称为对象的序列化,从持久设备上把对象读取到内存中称为对象的反序列化。ObjectOutputStream对象就是把内存中的一个对象,写到硬盘上,或者是把对象通过网络传递到网络的另外一端。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class People implements Serializable {
private int age;
private String name;
public People(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "People [age=" + age + ", name=" + name + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class IoDemo {
public static void main(String[] args) throws IOException {
ObjectOutputStream ooa = new ObjectOutputStream(new FileOutputStream("e:/lishuai.txt"));
People p = new People(24, "lishuai");
ooa.writeObject(p);
ooa.close();
}
}