gpt4 book ai didi

java - 使用 Java 将 byte[] 存储在 MongoDB 中

转载 作者:可可西里 更新时间:2023-11-01 09:56:38 25 4
gpt4 key购买 nike

我将一个文档插入到一个字段为 byte[] 的集合中。当我查询插入的文档以获取该字段时,它返回一个不同的 byte[]。我该如何解决?

byte[] inputBytes = ...

MongoCollection<Document> collection = _db.getCollection("collectionx");
Document doc = new Document("test", 1).append("val", inputBytes);
collection.insertOne(doc.getDocument());

MongoCursor<Document> result = collection.find(eq("test", 1)).iterator();
Document retrived_doc = cursor.next();
cursor.close();

byte[] outputBytes = ((Binary)retrived_doc.get("val")).getData();

// inputBytes = [B@719f369d
// outputBytes = [B@7b70cec2

最佳答案

问题不在于您的代码,而在于您如何检查两个数组(输入和输出数组)是否相等。您似乎只是在比较对两个结果调用 toString() 的结果。但是 toString() 没有被数组类型覆盖,所以它实际上是 Object.toString()它只返回对象的类型和哈希码:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

因此 [B@719f369d 表示:“字节数组”([B),哈希码为 0x719f369d。与数组内容无关。

在您的示例中,输入和输出数组是两个不同的对象,因此它们具有不同的内存地址和哈希码(事实上,hashCode() 也不会被数组类型覆盖) .

解决方案

如果要比较两个字节数组的内容,调用Arrays.equals(byte[], byte[]) .

如果要打印字节数组的内容,调用Arrays.toString(byte[])将内容转换为人类可读的 String

关于java - 使用 Java 将 byte[] 存储在 MongoDB 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30566905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com