This library allows you to encode and decode B-encoded documents.
Before:
Map<String,BEncodedValue> document = newHashMap<String, BEncodedValue>() {{
put("string", newBEncodedValue("value"));
put("number", newBEncodedValue(123456));
put("list", newBEncodedValue(newArrayList<BEncodedValue>() {{
add(newBEncodedValue("list-item-1"));
add(newBEncodedValue("list-item-2"));
}}));
put("dict", newBEncodedValue(newHashMap<String, BEncodedValue>() {{
put("123", newBEncodedValue("test"));
put("456", newBEncodedValue("thing"));
}}));
}};
ByteArrayOutputStreambaos = newByteArrayOutputStream();
BEncoder.encode(document, baos);
StringencodedDocument = newString(baos.toByteArray());After:
d
4:dict d
3:123 4:test
3:456 5:thing
e
4:list l
11:list-item-1
11:list-item-2
e
6:number i123456e
6:string 5:value
e
The library can do the reverse operation as well: decode.
First you need to read the torrent and decode it:
FiletorrentFile = "file.torrent";
FileInputStreaminputStream = newFileInputStream(torrentFile);
BDecoderreader = newBDecoder(inputStream);
Map<String, BEncodedValue> document = reader.decodeMap().getMap();Then you can start extracting information from it:
Stringannounce = document.get("announce").getString(); // StringsMap<String, BEncodedValue> info = document.get("info").getMap(); // MapsList<BEncodedValue> files = info.get("files").getList(); // ListsYou can check if a key exists using the 'containsKey' method as such:
if (document.containsKey("info")) {
System.out.println("The info field exists");
}The documentation page lists how you can add this library as a dependency of your project.
This library was created since no other viable libraries existed, and the ttorrent project contains a bunch of unecessary content. It is based on the work of Maxime Petazzoni.