import java.io.*;
import java.util.ArrayList;
import java.util.Date;
public class Buffertest {
public static void main(String[] args) throws Exception{
FileOutputStream fos=new FileOutputStream("a.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);
//用缓冲区来包装文件写入流
DataOutputStream dataOutputStream=new DataOutputStream(bos);
dataOutputStream.writeInt(1000);
dataOutputStream.writeDouble(123.456);
dataOutputStream.writeUTF("sadasd红啊a");
//bos.flush();// 刷新或者关闭都可以讲缓冲区的数据放到文件中
bos.close();
FileInputStream fis=new FileInputStream("a.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
DataInputStream dataInputStream=new DataInputStream(bis);
System.out.println(dataInputStream.readInt());//保持顺序,不然会乱
System.out.println(dataInputStream.readDouble());
System.out.println(dataInputStream.readUTF());
bis.close();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(fos);
// ArrayList<String> names=new ArrayList<>();
// names.add("张三");
// names.add("李四");
// names.add("王五");
ArrayList<Person> names=new ArrayList<>();
names.add(new Person("张三","13231231","男"));
names.add(new Person("李四","131231","女"));
names.add(new Person("王五","13231","男"));
for (Person p:names){
System.out.println(p);
}
objectOutputStream.writeObject(names);
/**
* 对对象进行串行化:如果将一个不能串行化的对象传递给writeObject方法,
那么它抛出一个NotSerializable Exception
对象只能在它的类实现了Serializable接口的情况下被串行化。
自己新建的类class1,新建的时候引入Serializable接口就行了
public class class1 implements Serializable{}
然后再根据提示在类里加一个private static final long serialVersionUID = 1L;就行了。
之后就可以使用writeObject(class1的实例)之类的函数了。
public interface Serializable {
}
*/
objectOutputStream.close();
FileInputStream fileInputStream=new FileInputStream("a.txt");
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
System.out.println(objectInputStream.readObject());
objectInputStream.close();
}
}
BufferInput/OutputStream ObjectInput/OutputStream
最新推荐文章于 2023-07-30 16:15:00 发布