开发者

Convert object attributes to always-same-length string [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Object attributes to same-length representation fo开发者_如何学Cr faster reading

I want to write my objects to a file where each object's representation is the same length, so I can jump to a section of the file to read without having to read the whole file.

This is necessary as the file will be read by many VMs and will be TBs in size. What's the best way of doing this? I've tried putting them in an array of ints to try to achieve this, but it seems this step must be unnecessary. I am passing each object back one at a time to be written by a different writer object. Cheers

// Convert Person attributes to integers and put in an array
int[] person = new int[8];
person[0] = age;
if (gender.equals("m")) {person[1] = 1;}
else {person[1] = 0;}
person[2] = children;
person[3] = goodHealth? 1:0;
person[4] = cars;
person[5] = avgWeekShopping;
person[6] = salary;
person[7] = smoker? 1:0;

return person;


It's faster if you write your values to a byte array. This can be written directly to any output stream. And you can save some space, like encoding the smoker flag in a single byte instead.

So you'd need to static methods, one that takes a bean and return a byte[], another one that takes a byte[] and creates a new bean. All arrays are equal size and you can easily calculate the offsets of individual datasets without the need of an extra index file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜