-
Data流 ->基本数据类型流,读入写出带有基本数据类型的数据+字符串数据
-
功能流,必须要包裹节点流使用(字节流)
-
DataInputStream 新增方法 readXxx()
-
DataOutputStream 新增方法 writeXxx()
*/
public class DataDemo {
public static void main(String[] args) throws IOException {
write(“D://test.txt”);
read(“D://test.txt”);
}public static void write(String dest) throws IOException{
DataOutputStream os=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
String s=“哈哈哈”;
double d=3.14;
boolean flag=false;
//写出
os.writeUTF(s); //写出字符串
os.writeDouble(d);
os.writeBoolean(flag);
//刷出
os.flush();
//关闭
os.close();
}public static void read(String src) throws IOException{
DataInputStream is=new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
//读入带有数据类型的数据 写出什么顺序读入什么顺序
String s=is.readUTF();
double d=is.readDouble();
boolean f=is.readBoolean();
System.out.println(s);
System.out.println(d);
System.out.println(f);
//关闭
is.close();
}
} -
对象流 序列化 公共流(节点流)
-
ObjectInputStream 反序列化输入流 新增方法 readObject()
-
ObjectOutputStream 序列化输出流 新增方法 writeObject()
-
注意:
-
先序列化后反序列化
-
输入写出的顺序必须一致
-
不是所有的类都能够序列化 实现接口java.io.Serializable
-
不是所有的属性都需要序列化 transient
-
如果父类实现了序列化接口,子类中所有的内容都与能力序列化
-
如果子类实现了序列化接口,但是父类没有实现,子类只能序列化自己的内容
-
静态的内容不能序列化
*/
public class ObjectDemo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
out(“D://lalala.txt”);
in(“D://lalala.txt”);
}
//序列化输出流
public static void out(String dest) throws FileNotFoundException, IOException{
//选择流 建立联系
ObjectOutputStream os=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
//准备数据
Person p=new Person(01,"李四",80);
//写出
os.writeObject(p);
//关闭 +输出
os.close();
p.setId(100);
p.setName("hahahahha");
}
//反序列化输入流
public static void in(String src) throws FileNotFoundException, IOException, ClassNotFoundException{
//选择流 建立联系
ObjectInputStream is=new ObjectInputStream(new BufferedInputStream(new FileInputStream(src)));
//写出
Object o=is.readObject();
if(o instanceof Person){
Person p=(Person)o;
System.out.println(p.getId());
System.out.println(p.getName());
System.out.println(p.getAge());
}
//关闭
is.close();
}
}
class Person implements Serializable{
private static int id;
private String name;
private transient int age;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}