I put together this self-contained piece of Java code to prepare a .torrent file with a single file.
A .torrent file is created by calling createTorrent() , passing the name of the .torrent file, the name of the shared file, and the tracker URL.
createTorrent() uses hashPieces() to hash fragments of a file using the Java MessageDigest class. Then createTorrent() prepares a meta-information dictionary containing torrent metadata. This dictionary is then serialized in its own bencode format using the encode*() methods and saved in the .torrent file.
See the BitTorrent Specification for more details.
public class Torrent { private static void encodeObject(Object o, OutputStream out) throws IOException { if (o instanceof String) encodeString((String)o, out); else if (o instanceof Map) encodeMap((Map)o, out); else if (o instanceof byte[]) encodeBytes((byte[])o, out); else if (o instanceof Number) encodeLong(((Number) o).longValue(), out); else throw new Error("Unencodable type"); } private static void encodeLong(long value, OutputStream out) throws IOException { out.write('i'); out.write(Long.toString(value).getBytes("US-ASCII")); out.write('e'); } private static void encodeBytes(byte[] bytes, OutputStream out) throws IOException { out.write(Integer.toString(bytes.length).getBytes("US-ASCII")); out.write(':'); out.write(bytes); } private static void encodeString(String str, OutputStream out) throws IOException { encodeBytes(str.getBytes("UTF-8"), out); } private static void encodeMap(Map<String,Object> map, OutputStream out) throws IOException{
Code editing: Make it a little more compact, consolidate the visibility of methods, use character literals where necessary, use instanceof Number . And just recently I read a file using block I / O, because I'm trying to use it for real and byte I / O just slowly,
Alexandre Jasmin
source share