Java 对象读、写进二进制文件
日期: 2019-12-30 分类: 跨站数据测试 351次阅读
实体准备
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();
}
}
}
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
标签:Java
精华推荐