简体   繁体   中英

Java: What is the best way to write object data members to a file?

I'm in the middle of a Java project where one of the things I need to do to make it work is to write and read objects from disk. Specifically, I need to write and then later load a given object's data members from a single RandomAccessFile with fixed-sized records for each object. This file represents a partition with fixed sized disk blocks.

Now what I've done is to explicitly convert every data member to bytes using ByteBuffer . I then wrote these to file, allowing the data to be reloaded later to instantiate a new object with identical values for its data members. The thing I don't like about this approach is that every single data member must be explicitly converted and put into the ByteBuffer and then written. Loading just does the opposite, converting all the bytes back and storing them in an object of the appropriate type.

The approach I used above just seems overly convoluted. Is there a better way, easier way? What I was thinking of is something similar to what you can do I do in C++. In the past I've stored and reloaded object data from fixed-size indexed records pretty easily using a pointer to the object and then writing all the bytes from there with ofstream (or similar), after casting the pointer to const char * using reinterpret_cast . Loading the file with ifstream (or similar) was just as simple, simply using index * sizeOf(Foo) to calculate the file pointer offset and then seeking before reading into memory from file.

Is there something similar to this approach in Java?

It sounds like what you're looking for is an ObjectOutputStream which allows you to serialize arbitrary (but must implement Serializable ) objects to a byte array (or in this case stream) which can then be written to disk. That by itself won't support your random access needs, but it will be a good part of the solution that doesn't require custom adapters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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