Advertisement
Guest User

Java bencode - BEncoder.java

a guest
Apr 11th, 2010
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | None | 0 0
  1. package bencode;
  2.  
  3. import java.io.OutputStream;
  4. import java.io.IOException;
  5. import java.util.List;
  6. import java.util.ArrayList;
  7. import java.util.Map;
  8. import java.util.Iterator;
  9. import java.util.Collections;
  10.  
  11. public class BEncoder {
  12.  
  13.     public static void bencode(long n, OutputStream out) throws IOException {
  14.        
  15.         out.write('i');
  16.         out.write(Long.toString(n).getBytes());
  17.         out.write('e');
  18.        
  19.     }
  20.  
  21.     public static void bencode(String s, OutputStream out) throws IOException {
  22.        
  23.         byte[] bytes = s.getBytes("UTF-8");
  24.         out.write(Integer.toString(bytes.length).getBytes());
  25.         out.write(':');
  26.         out.write(bytes);
  27.        
  28.     }
  29.  
  30.     public static void bencode(List list, OutputStream out)
  31.             throws IOException, Exception {
  32.  
  33.         out.write('l');
  34.         Iterator it = list.iterator();
  35.         while (it.hasNext()) {
  36.             Object o = it.next();
  37.             bencode(o, out);
  38.         }
  39.         out.write('e');
  40.  
  41.     }
  42.  
  43.     public static void bencode(Map map, OutputStream out)
  44.             throws IOException, Exception {
  45.  
  46.         out.write('d');
  47.         List keys = new ArrayList(map.keySet());
  48.         Collections.sort(keys);
  49.         Iterator it = keys.iterator();
  50.        
  51.         while (it.hasNext()) {
  52.             Object o = it.next();
  53.             bencode((String) o, out);
  54.             bencode(map.get(o), out);
  55.         }
  56.        
  57.         out.write('e');
  58.        
  59.     }
  60.  
  61.     public static void bencode(Object o, OutputStream out)
  62.             throws IOException, Exception {
  63.  
  64.         if (o instanceof String) {
  65.             bencode((String) o, out);
  66.         } else if (o instanceof Number) {
  67.             bencode(((Number) o).longValue(), out);
  68.         } else if (o instanceof List) {
  69.             bencode((List) o, out);
  70.         } else if (o instanceof Map) {
  71.             bencode((Map) o, out);
  72.         } else {
  73.             throw new Exception("Type not supported: " + o.getClass().getName());
  74.         }
  75.  
  76.     }
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement