MongoDb Java中的二进制到字符串

时间:2017-04-28 11:35:08

标签: java mongodb bson

您好我使用MongoDb数据库,我必须将MongoDb数据库中的所有内容作为二进制形式。现在在servlet部分我需要获取id并将bson二进制转换为String以在iFrames中写入。如何使用Java将MongoDb中的二进制转换为字符串?

JAVA CODES。

    //Not quite working.

    public String giveSelected(String id){
    MongoClient mongoClient = new MongoClient("localhost",27017);
    MongoDatabase database = mongoClient.getDatabase("dbTest");
    MongoCollection<Document> collection = database.getCollection("colTest");
    Document myDoc = collection.find(eq("_id", id)).first();
    String str=myDoc.getString("content");
    return str;
}

JSP CALL:

 //str is the String form of needed content Binary.
 <script>
 function iFramefunc(){
 var s = document.getElementById('iframe');
 s.contentDocument.documentElement.innerHTML="<%=str%>";
 s.contentDocument.close();
 }
 </script>
 <iframe id="iframe" onload="iFramefunc()"></iframe>

1 个答案:

答案 0 :(得分:0)

您可能还想压缩内容并存储压缩的二进制数据。这是一个例子:

private static byte[] compress(String str) throws IOException {
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.close();
    byte[] compressedString = obj.toByteArray();
    return compressedString;
}

private static String uncompress(byte[] compressedContent) throws IOException {
    GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressedContent));
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
    String line;
    StringBuilder out = new StringBuilder();
    while ((line = bufferedReader.readLine()) != null) {
        out.append(line);
    }  
    return out.toString();
}

private static void readWrite() throws IOException {
    MongoClient mongoClient = new MongoClient("localhost",27017);
    MongoDatabase database = mongoClient.getDatabase("dbTest");
    MongoCollection<Document> collection = database.getCollection("colTest");
    collection.drop();

    // Write
    String str = "aaaaaaaaaaaaaaaaaaaaBBBBBBBBBBBBBBBBBBBBBBBBBBBccccccccccccccccccc";
    byte[] compressedString = compress(str);
    String id = "abc";
    Document doc = new Document("content", compressedString).append("_id", id);
    collection.insertOne(doc);

    // Read
    Document myDoc = collection.find(eq("_id", id)).first();
    byte[] compressedContent = ((Binary)myDoc.get("content")).getData();
    String content = uncompress(compressedContent);
    System.out.println(content);
}