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();
            }
        }

    }

おすすめ

転載: blog.csdn.net/polixiaohai/article/details/103771006