如何用java或clojure解码bson
我想把BSON文件解码成Clojure地图
这是我的代码:
(ns decode
(:require [clojure.java.io :as cji])
(:import [org.bson BasicBSONObject BasicBSONEncoder BasicBSONDecoder]))
(defonce encoder (BasicBSONEncoder.))
(defonce decoder (BasicBSONDecoder.))
(defn read-file [file-path]
(with-open [reader (cji/input-stream file-path)]
(let [length (.length (clojure.java.io/file file-path))
buffer (byte-array length)]
(.read reader buffer 0 length)
buffer)))
(defn bson2map [^Byte b]
(->> (.readObject decoder b) (.toMap) (into {})))
(defn read-bson
[path]
(clojure.walk/keywordize-keys (bson2map (read-file path))))
但是当我解码像这样的BSON文件时(r/read-bson "test.bson")
,它只解码第一条记录,我想解码所有记录。{
然后我发现了一个名为LazyBSONDecoder
的类,编写了一些java代码,它可以工作,它可以解码所有记录
import org.bson.LazyBSONDecoder;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("./_Installation.bson");
LazyBSONDecoder decoder = new LazyBSONDecoder();
Object obj;
int count = 0;
try {
do {
obj = decoder.readObject(in);
System.out.println(obj);
count++;
} while (obj != null);
} catch (Exception e) {
// ignore
}
System.out.println(count);
}
}
因此,我更改了Clojure代码,将BasicBSONDecoder
替换为LazyBSONDecoder
,但它总是只解码第一条记录
(defonce decoder (LazyBSONDecoder.))
(defn bson2map [^Byte b]
(do (print (.readObject decoder b))
(print (.readObject decoder b))
(print (.readObject decoder b))))
# 1 楼答案
请看这个代码LazyBSONDecoder
函数
bson2map
参数应该是一个inputStream,而不是字节数组,如果它是字节数组,它将返回一个新的ByteArrayInputStream
,所以我总是得到第一条记录