java二进制文件操作
我有一堆不同的对象(和 objec 类型),我想将它们写入二进制文件。首先,我需要文件的结构如下:
`Object type1
obj1, obj2 ...
Object type2
obj1, obj2...
....
作为一个二进制文件,这不能帮助用户阅读它,但我想要一个结构,以便我可以搜索、删除或按类型添加对象,而不是解析整个文件。这是我不知道该怎么做的事情。这可能吗?
I have a bunch of different objects(and objec types) that i want to write to a binary file. First of all i need the file to be structured like this:
`Object type1
obj1, obj2 ...
Object type2
obj1, obj2...
....
Being a binary file this doesn't help a user read it, but i want to have a structure so i can search, delete or add an object by it's type, not parsing the entire file. And this is something i don't know how to do. Is this even posible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在文件的开头(或其他位置)维护一个标头来标记每个对象的位置和长度。
标头的类型和布局在很大程度上取决于您计划如何读取和写入文件。例如,如果您计划按名称检索对象,则文件中可以包含类似以下内容
并知道
object1
从文件中的偏移量 400 开始,长度为 1050 字节。由于您似乎想要存储不同类型的对象,因此您可能需要向标头添加一些附加数据。
请注意以下事项:
但我不知道有任何库可以帮助您实现此类功能。我很确定有一些。也许有人可以建议。 另
--
一种解决方案是使用 ZipFile(Java 本身支持)之类的东西并将每个对象编写为不同的 ZipEntry,这样您就不必自己管理对象分离。不用担心知道您想要的确切 ZipEntry。
You will have to maintain a header at the beginning of the file (or somewhere else) to mark the position and length of each of your objects.
The kind and layout of the header depend a lot on how you plan to read and write into the file. For example if you plan to retrieve the objects by name, you could have in your file something like this
And know that
object1
starts at the offset 400 in the file, and has a length of 1050 bytes.Since it seems that you have different types of objects that you want to store, you will probably need to add some additional data to your header.
Take care of the following:
I'm not aware of any library that will help you implement such a feature but I'm pretty sure there are some. Maybe someone will be able to suggest one.
--
Another solution would be to use something like a ZipFile (which is natively supported by Java) and write each of your objects as a differenz ZipEntry. This way you won't have to manage object separation yourself, and will only need to worry about knowing the exact ZipEntry you want.