Java图书管理系统练习程序(三)

Java图书管理系统练习程序(三)

本部分内容主要实现将用户信息写入文件中,并在程序执行时,将文件中的用户信息读入到内存中,实现用户信息的存储。

将Java对象序列化后,可以将对象保存在文件中,或者在网络中直接进行传输。

如果要实现序列化,只需让该类实现Serializable接口即可。该接口只是一个标记接口,不需要实现任何方法,它只是表明该类的实例化对象是可以序列化的。

一、将Java对象通过序列化实现读写

1.创建ObjectOutputStream输出流

File file=new File("user.txt");
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file,false));

其中的file,表示存储数据的文件;false表示是否追加

2.将序列化对象输出到文件中

oos.writeObject(users);
oos.flush();//刷新方法,将数据立刻输出,或者等到流内满了自动调用flush刷新,将数据输出

3.关闭ObjectOutPutStream对象

oos.close();

4.创建ObjectInputStream输入流

File file=new File("user.txt");
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));

5.读取序列化对象

ois.readObject();

6.关闭ObjectOutPutStream对象

ois.close();

二、在util包中创建FileRw类,实现对用户对象集合的文件读写操作

package sky.book.util;

import sky.book.bean.User;

import java.io.*;
import java.util.List;

public class FileRW {
    /**
     * 将用户集合对象写入到文件中
     * @param users
     * @return
     */
    public static boolean writeDateToFile(List<User> users){
        File file=new File("user.txt");
        try {
            ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file,false));
            oos.writeObject(users);
            oos.flush();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static List<User> readDateFromFile(){
        File file=new File("user.txt");
        ObjectInputStream ois=null;
        List<User> users=null;
        try {
            ois=new ObjectInputStream(new FileInputStream(file));
            users= (List<User>) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally{
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return users;
    }
}

猜你喜欢

转载自my.oschina.net/u/3537796/blog/2353500