从数据库中获取字节数组

时间:2014-04-25 23:52:33

标签: java angularjs mongodb

我想从数据库(mongo)获取一个字节数组(java)并对其进行操作,将其作为原始图像发送到DOM等。

BasicDBObject condition = new BasicDBObject("_id", new ObjectId(_id));
    DBObject dataset = DataAccess.GetInstanceClass().Getdatasets().findOne(condition);
    byte[] image = (byte[]) dataset.get("image").toString().getBytes();

    String s = new String(image);
    System.out.println("provider: " + s);

这只会返回 信息:提供者:[B @ 3b249009

1 个答案:

答案 0 :(得分:0)

这样做的:

System.out.println("provider: " + image);

或:

System.out.println("provider: " + new String(image));

两者都导致打印数组的默认toString(),这是指向数组的指针(在您的情况下,相当丑陋的[B@3b249009

如果你想查看一个更有用的字节数组的字符串表示,你可以从this question找到答案:

System.out.println("byte array as pretty string: " + Arrays.toString(image));

此外,正如您所说,您不需要(事实上,不应该)

dataset.get("image").toString().getBytes();

你把数据放在各种各样的破坏中。

我编写了一个简短的测试来演示如何从MongoDB中获取字节数组,以及使用Arrays.toString()方法将其作为默认字符串编写的差异:

@Test
public void shouldBeAbleToGetANiceStringRepresentationOfAByteArray() {
    // given
    ObjectId id = new ObjectId();
    byte[] bytes = {1,2,3,4};
    collection.insert(new BasicDBObject("_id", id).append("image", bytes));

    // when 
    BasicDBObject condition = new BasicDBObject("_id", id);
    DBObject dataset = collection.findOne(condition);
    byte[] image = (byte[]) dataset.get("image");

    // then
    // this instanceof is actually pointless, since casting it to a byte array above means it must be a byte array, but the point is to demonstrate it's not a String
    assertTrue(image instanceof byte[]);

    assertThat(image.toString(), startsWith("[B@"));
    assertThat(image.toString().length(), is(11));
    System.out.println("byte array toString(): " + image);

    assertThat(Arrays.toString(image), is("[1, 2, 3, 4]"));
    System.out.println("byte array as pretty string: " + Arrays.toString(image));
}