Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package bencode;
- import java.io.OutputStream;
- import java.io.IOException;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Map;
- import java.util.Iterator;
- import java.util.Collections;
- public class BEncoder {
- public static void bencode(long n, OutputStream out) throws IOException {
- out.write('i');
- out.write(Long.toString(n).getBytes());
- out.write('e');
- }
- public static void bencode(String s, OutputStream out) throws IOException {
- byte[] bytes = s.getBytes("UTF-8");
- out.write(Integer.toString(bytes.length).getBytes());
- out.write(':');
- out.write(bytes);
- }
- public static void bencode(List list, OutputStream out)
- throws IOException, Exception {
- out.write('l');
- Iterator it = list.iterator();
- while (it.hasNext()) {
- Object o = it.next();
- bencode(o, out);
- }
- out.write('e');
- }
- public static void bencode(Map map, OutputStream out)
- throws IOException, Exception {
- out.write('d');
- List keys = new ArrayList(map.keySet());
- Collections.sort(keys);
- Iterator it = keys.iterator();
- while (it.hasNext()) {
- Object o = it.next();
- bencode((String) o, out);
- bencode(map.get(o), out);
- }
- out.write('e');
- }
- public static void bencode(Object o, OutputStream out)
- throws IOException, Exception {
- if (o instanceof String) {
- bencode((String) o, out);
- } else if (o instanceof Number) {
- bencode(((Number) o).longValue(), out);
- } else if (o instanceof List) {
- bencode((List) o, out);
- } else if (o instanceof Map) {
- bencode((Map) o, out);
- } else {
- throw new Exception("Type not supported: " + o.getClass().getName());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement