实体准备
public class Arc implements Serializable{
private Node src;
private Node dest;
......
}
读取
RandomAccessFile randomAccessFile = new RandomAccessFile(fileNodePath, "r");
public Arc read(RandomAccessFile dataInputStream) {
Arc arc = null;
ObjectInputStream obj = null;
ByteArrayInputStream byt = null;
try {
Integer length = dataInputStream.readInt();
byte[] bytes = new byte[length];
dataInputStream.read(bytes);
byt = new ByteArrayInputStream(bytes);
obj = new ObjectInputStream(byt);
arc = (Arc) obj.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
obj.close();
byt.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return arc;
}
写入
RandomAccessFile randomAccessFile = new RandomAccessFile(fileNodePath, "rw");
public void write(RandomAccessFile dataOutputStream) {
ObjectOutputStream obj = null;
ByteArrayOutputStream byt = null;
try {
byt = new ByteArrayOutputStream();
obj = new ObjectOutputStream(byt);
obj.writeObject(this);
dataOutputStream.writeInt(byt.toByteArray().length);
dataOutputStream.write(byt.toByteArray());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
obj.close();
byt.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}