简体   繁体   English

java,用DataOutputStream写入数据大小

[英]java, writing data size with DataOutputStream

I have a series of objects which write their data out to a file via DataOutputStream.我有一系列对象,它们通过 DataOutputStream 将数据写入文件。

As my application file format evolves, I will be adding further data objects to it, which should be able to be read by "older" versions of the application.随着我的应用程序文件格式的发展,我将向其中添加更多数据对象,这些对象应该能够被“旧”版本的应用程序读取。

To be able to do this, I am needing to preface the objects data with a size value indicating the number of bytes that the current object will take up.为了能够做到这一点,我需要在对象数据前面加上一个大小值,该值指示当前对象将占用的字节数。

However, as this data can be a variable size, notably when handling strings, I cannot know beforehand what the size will be.但是,由于这些数据的大小可能是可变的,特别是在处理字符串时,我无法事先知道大小是多少。

Is there a way to "pre-write" to a byte buffer, as if it were a DataOutputStream ( methods in particular - writeByte, writeShort, writeInt, writeUTF ) which will enable me to get back the byte length of the data before writing it out to the DataOutputStream ?有没有办法“预写”到字节缓冲区,就好像它是一个 DataOutputStream (特别是方法 - writeByte, writeShort, writeInt, writeUTF ),这将使我能够在写入之前取回数据的字节长度到 DataOutputStream ? Doing this will enable me to skip over newer data objects that older versions of the application does understand.这样做将使我能够跳过旧版本应用程序可以理解的新数据对象。

Regular Java serialization is not that great for a variety of reasons.由于各种原因,常规 Java 序列化并不是那么好。 One of the most important ones is that it's very brittle, and tends not to be "future proof".最重要的问题之一是它非常脆弱,而且往往不是“面向未来的证明”。 If possible, I'd suggest you use a different serialization format, especially if you specifically mention that you plan on adding fields to the class you serialize.如果可能,我建议您使用不同的序列化格式,特别是如果您特别提到您计划向序列化的类添加字段。

Formats such as Protobuf , and JSON have Java libraries with nice APIs, and good forwards/backwards compatibility features.诸如ProtobufJSON 之类的格式具有带有良好 API 和良好的向前/向后兼容性功能的 Java 库。 In most cases, it would be far simpler to Serialize your data into a more convenient format, than solving the problems of the existing one.在大多数情况下,将数据序列化为更方便的格式要比解决现有格式的问题简单得多。

As you can see here , you could use java.lang.instrument.Instrumentation in this way:正如你在这里看到的,你可以这样使用java.lang.instrument.Instrumentation

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

and then calculate the size in bytes of your object:然后计算对象的大小(以字节为单位):

public static void main(String [] args) {
   Object myObject = ...;
        System.out.println(ObjectSizeFetcher.getObjectSize(myObject));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM