网站是不是用cms做的,临沂罗庄做网站,网站制作哪家便宜,网站建设开发ppt模板下载注意事项:
1.创建的对象必须实现序列化接口,如果属性也是类#xff0c;那么对应的类也要序列化
2.读写文件路径问题
3.演示一个例子
#xff08;1#xff09;操作的实体类FileModel#xff0c;实体类中有Map,HashMap这些自带的本身就实现了序列化。
public class File…注意事项:
1.创建的对象必须实现序列化接口,如果属性也是类那么对应的类也要序列化
2.读写文件路径问题
3.演示一个例子
1操作的实体类FileModel实体类中有Map,HashMap这些自带的本身就实现了序列化。
public class FileModel implements Serializable {public MapString, FileModel subMap new HashMapString, 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();MapString, 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);}}
截图: