注意事项:
1.创建的对象必须实现序列化接口,如果属性也是类,那么对应的类也要序列化
2.读写文件路径问题
3.演示一个例子
(1)操作的实体类FileModel,实体类中有Map,HashMap这些自带的本身就实现了序列化。
public class FileModel implements Serializable {public Map<String, FileModel> subMap = new HashMap<String, FileModel>();private String name; private int attr; private int startNum; private int size; private String content;private FileModel father = null; public FileModel(String name){this.name = name;}public FileModel(String name, int startNum, int size) {this.name = name;this.attr = 2;this.startNum = startNum;this.size = size;}public FileModel(String name, int startNum) {this.name = name;this.attr = 3;this.startNum = startNum;this.size = 0;}//getter,setter方法...
}
(2)创建对象,并将其写到mode.dat文件当中
public static void write() {FileModel root = new FileModel("root");//不占用FileModel fileModel = new FileModel("kk.txt", 2);fileModel.setSize(2);FileModel fileModel1 = new FileModel("aa.txt", 3);root.subMap.put("kk.txt", fileModel1);root.subMap.put("aa.txt", fileModel1);try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file-system/src/model.dat"))) {oos.writeObject(root);oos.flush();} catch (IOException e) {e.printStackTrace();}}
这里注意路径问题,
首先,看一下我的项目结构,可以使用相对路径或者绝对路径来读写,使用绝对路径,即从磁盘开始,即“D:\operating-system\file-system\src\model.dat” ; 使用相对路径,即相对当前项目目录operating-system,如上面代码中的“file-system/src/model.dat”。
(4)从model.dat文件当中读取
public static void read() {try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file-system/src/model.dat"))){FileModel fileModel = (FileModel)ois.readObject();String name = fileModel.getName();Map<String, FileModel> subMap = fileModel.subMap;System.out.println(name);subMap.forEach((s, fileModel1) -> System.out.println(s + "----->" + fileModel1.getName()));}catch (IOException e){e.printStackTrace();} catch (ClassNotFoundException e) {throw new RuntimeException(e);}}
截图: