其他流..

序列化:把对象存储到文件中

package MONA.demo10_序列化流;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 序列化
 * Java的对象,将对象存入文件中
 * 反序列化
 * 将文件中的对象读取到Java内存中
 *
 * 在序列化对一个对象时会出现异常:
 *      NotSerializableException
 *      解决:需要实现序列化的类
 */
public class Demo01 {
    //        Serializable:序列化的接口
    public static void main(String[] args) throws Exception{
        Student s = new Student("李四",19);
        //将s对象存入文件中
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student"));
        oos.writeObject(s);
        oos.close();
        System.out.println("写入成功");
    }
}
class Student implements Serializable {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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;
    }
}

将文件中的对象读取到内存中

package MONA.demo10_序列化流;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * 反序列化
 *  将文件中的对象读取到内存中
 */
public class Demo02 {
    public static void main(String[] args) throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student"));
        //读取
        Object o = ois.readObject();
        //将对象转回真正的类型
        Student s = (Student) o;
        System.out.println(s.getName());
        System.out.println(s.getAge());
    }
}

eclipse版本需要添加序列号

对象流细节问题

ArrayList也实现了接口Serializable
package MONA.demo10_序列化流;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        ArrayList<String> names = new ArrayList<>();
        names.add("李四");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student"));
        oos.writeObject(names);
        System.out.println("写入成功");
    }
}

 打印流

package MONA.demo12_打印流;

import java.io.PrintStream;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        PrintStream p = new PrintStream("1.txt");
        p.write(97);
        p.println(97);
        System.out.println("成功");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值