Young87

SmartCat's Blog

So happy to code my life!

游戏开发交流QQ群号60398951

当前位置:首页 >跨站数据测试

Java 对象读、写进二进制文件

实体准备

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

上一篇: lerna管理前端packages的最佳实践

下一篇: 全网目前最全python例子(附源码)

精华推荐