Class TorrentBuilder

java.lang.Object
com.frostwire.jlibtorrent.TorrentBuilder

public final class TorrentBuilder extends Object
Fluent builder for creating .torrent files from local files and directories.

TorrentBuilder provides a convenient API for creating BitTorrent metafiles (.torrent) from local files and directories. It supports all modern torrent features including trackers, DHT nodes, web seeds, metadata, and hash computation with progress tracking.

Understanding Torrent Creation:
A .torrent file is a bencoded metadata file containing:

  • File Information: Names, sizes, and pieces (chunks)
  • Piece Hashes: SHA-1 or SHA-256 hashes for verification
  • Announce URLs: Tracker URLs organized by tier/priority
  • DHT Nodes: Bootstrap nodes for decentralized peer discovery
  • Web Seeds: HTTP/FTP URLs for web seeding
  • Metadata: Comment, creator, creation time, private flag

Basic Torrent Creation:

 // Create a torrent for a single file
 TorrentBuilder builder = new TorrentBuilder();
 builder.path(new File(\"/path/to/file.iso\"));
 builder.pieceSize(262144);  // 256 KB pieces
 builder.addTracker(\"http://tracker.example.com:6969/announce\", 0);
 builder.comment(\"My ISO image\");
 builder.creator(\"My App v1.0\");

 TorrentBuilder.Result result = builder.build();
 Entry torrentEntry = result.entry();
 // Save torrentEntry to file...
 

Multi-File Torrent:

 // Create a torrent for a directory
 TorrentBuilder builder = new TorrentBuilder();
 builder.path(new File(\"/path/to/directory\"));
 builder.pieceSize(16384);  // 16 KB pieces for flexibility
 builder.addTracker(\"http://primary-tracker.com/announce\", 0);  // Tier 0
 builder.addTracker(\"http://backup-tracker.com/announce\", 1);   // Tier 1
 builder.addNode(new Pair<>(\"router.bittorrent.com\", 6881));\n * builder.addUrlSeed(\"http://mirror.example.com/data/\");\n *
 TorrentBuilder.Result result = builder.build();
 

Piece Size Considerations:

 // Piece sizes must be power of 2, between 16 KiB and 16 MiB
 // Common sizes:
 builder.pieceSize(16384);    // 16 KiB - many small pieces, larger .torrent file
 builder.pieceSize(32768);    // 32 KiB
 builder.pieceSize(65536);    // 64 KiB
 builder.pieceSize(262144);   // 256 KiB - good default for large files
 builder.pieceSize(1048576);  // 1 MiB - for very large files

 // Auto-sizing: set to 0 to let TorrentBuilder choose
 builder.pieceSize(0);  // Will be ~40 KB torrent file size
 

Tracker Organization:

 // Trackers are tried in tier order (priority)
 // Tier 0 tried first, then tier 1 if all tier 0 fail, etc.
 builder.addTracker(\"http://tier0-a.com/announce\", 0);
 builder.addTracker(\"http://tier0-b.com/announce\", 0);  // Alternative tier 0
 builder.addTracker(\"http://tier1-backup.com/announce\", 1);
 builder.addTracker(\"http://tier2-last-resort.com/announce\", 2);
 

Progress Tracking:

 TorrentBuilder builder = new TorrentBuilder();
 // ... setup configuration ...

 builder.listener(new TorrentBuilder.Listener() {
     public boolean accept(String filename) {
         // Return true to include, false to skip
         return !filename.startsWith(\".\");  // Skip hidden files
     }

     public void progress(int pieceIndex, int numPieces) {
         // Called as hashes are computed
         double percent = (double) pieceIndex / numPieces * 100;
         System.out.println(String.format(\"Hashing: %.1f%%\", percent));
     }
 });

 TorrentBuilder.Result result = builder.build();
 

DHT Nodes and Web Seeds:

 // DHT nodes for decentralized peer discovery (tracker-less torrent)
 builder.addNode(new Pair<>(\"router.bittorrent.com\", 6881));
 builder.addNode(new Pair<>(\"router.transmissionbt.com\", 6881));
 builder.addNode(new Pair<>(\"dht.transmissionbt.com\", 6881));

 // Web seeds for HTTP/FTP distribution
 builder.addUrlSeed(\"http://cdn.example.com/downloads/file.iso\");
 builder.addUrlSeed(\"ftp://mirror.example.com/file.iso\");
 

Metadata and Privacy:

 builder.comment(\"ISO image for my project\");
 builder.creator(\"My Torrent Creator v1.0\");
 builder.creationDate(System.currentTimeMillis() / 1000);  // UNIX timestamp
 builder.priv(true);  // Private torrent (DHT/PEX disabled)
 

Flags for Advanced Features:

 // Enable specific creation options
 builder.flags(TorrentBuilder.PADDING);  // Add padding files for alignment
 builder.flags(TorrentBuilder.SYMLINKS);  // Preserve symbolic links
 builder.flags(TorrentBuilder.V2_ONLY);  // Only v2 metadata (modern clients)
 

Accessing Build Results:

 TorrentBuilder.Result result = builder.build();

 // Get bencoded torrent data
 Entry torrentEntry = result.entry();

 // Get torrent metadata
 int numPieces = result.numPieces();
 int pieceLength = result.pieceLength();

 // Get individual piece size
 int lastPieceSize = result.pieceSize(result.numPieces() - 1);

 // Save to file
 byte[] torrentData = torrentEntry.bencode();
 Files.write(Paths.get(\"file.torrent\"), torrentData);
 

Builder Pattern:

TorrentBuilder uses the fluent builder pattern. All configuration methods return the builder itself, enabling method chaining for clean, readable code.

Performance Notes:

  • Hash computation is CPU-intensive; progress callback helps monitor long operations
  • Smaller pieces = larger .torrent file and more I/O
  • Larger pieces = smaller .torrent file but less granular progress
  • Call build() only once; reuse TorrentBuilder for multiple torrents
See Also:
  • Field Details

    • MODIFICATION_TIME

      public static final com.frostwire.jlibtorrent.swig.create_flags_t MODIFICATION_TIME
      This will include the file modification time as part of the torrent. This is not enabled by default, as it might cause problems when you create a torrent from separate files with the same content, hoping to yield the same info-hash. If the files have different modification times, with this option enabled, you would get different info-hashes for the files.
    • V2_ONLY

      public static final com.frostwire.jlibtorrent.swig.create_flags_t V2_ONLY
      Do not generate v1 metadata. The resulting torrent will only be usable by clients which support v2. This requires setting all v2 hashes, with set_hash2() before calling generate(). Setting v1 hashes (with set_hash()) is an error with this flag set.
    • V1_ONLY

      public static final com.frostwire.jlibtorrent.swig.create_flags_t V1_ONLY
      Do not generate v2 metadata or enforce v2 alignment and padding rules this is mainly for tests, not recommended for production use. This requires setting all v1 hashes, with set_hash(), before calling generate(). Setting v2 hashes (with set_hash2()) is an error with this flag set.
    • CANONICAL_FILES

      public static final com.frostwire.jlibtorrent.swig.create_flags_t CANONICAL_FILES
      This flag only affects v1-only torrents, and is only relevant together with the v1_only_flag. This flag will force the same file order and padding as a v2 (or hybrid) torrent would have. It has the effect of ordering files and inserting pad files to align them with piece boundaries.
  • Constructor Details

    • TorrentBuilder

      public TorrentBuilder()
  • Method Details

    • path

      public File path()
    • path

      public TorrentBuilder path(File value)
      Sets the path by the specified file
    • pieceSize

      public int pieceSize()
      The ``piece_size`` is the size of each piece in bytes. It must be a power of 2 and a minimum of 16 kiB. If a piece size of 0 is specified, a piece_size will be set automatically.
    • pieceSize

      public TorrentBuilder pieceSize(int value)
      The size of each piece in bytes. It must be a multiple of 16 kiB. If a piece size of 0 is specified, a pieceSize will be calculated such that the torrent file is roughly 40 kB.
    • flags

      public com.frostwire.jlibtorrent.swig.create_flags_t flags()
      create_flags_t is a type alias that simplifies the usage of the bitfield_flag structure for a specific case within the libtorrent namespace.

      The bitfield_flag structure in the provided code is a utility for managing flags in a bitfield, which is essentially a data structure that compactly stores bits.

      create_flags_t is a type alias for bitfield_flag<std::uint32_t, create_flags_tag>, specifically designed to handle creation flags in libtorrent.

      It provides a compact, efficient way to manage binary flags using bitwise operations, with the additional type safety provided by the create_flags_tag.

    • flags

      public TorrentBuilder flags(com.frostwire.jlibtorrent.swig.create_flags_t value)
      Specifies options for the torrent creation. It can be any combination of the flags defined by create_flags_t
    • alignment

      public int alignment()
    • alignment

      public TorrentBuilder alignment(int value)
      Used when pad files are enabled. This is the size eligible files are aligned to. The default is -1, which means the piece size of the torrent.
    • comment

      public String comment()
      The comment for the torrent. The comment in a torrent file is optional.
    • comment

      public TorrentBuilder comment(String value)
      Sets the comment for the torrent. The comment in a torrent file is optional.
    • creator

      public String creator()
      The creator of the torrent. This is optional.
    • creator

      public TorrentBuilder creator(String value)
      Sets the creator of the torrent. This is optional.
    • creationDate

      public long creationDate()
      The "creation time" field. Defaults to the system clock at the time of construction. The timestamp is specified in seconds, posix time. If the creation date is set to 0, the "creation date" field will be omitted from the generated torrent.
    • creationDate

      public TorrentBuilder creationDate(long timestamp)
      Set the "creation time" field. Defaults to the system clock at the time of construction. The timestamp is specified in seconds, posix time. If the creation date is set to 0, the "creation date" field will be omitted from the generated torrent.
    • urlSeeds

      public List<String> urlSeeds()
    • addUrlSeeds

      public TorrentBuilder addUrlSeeds(List<String> value)
      This adds a list of url seeds to the torrent. You can have any number of url seeds. For a single file torrent, this should be an HTTP url, pointing to a file with identical content as the file of the torrent. For a multi-file torrent, it should point to a directory containing a directory with the same name as this torrent, and all the files of the torrent in it.
    • addUrlSeed

      public TorrentBuilder addUrlSeed(String value)
      This adds a URL seed to the torrent. You can have any number of url seeds. For a single file torrent, this should be an HTTP url, pointing to a file with identical content as the file of the torrent. For a multi-file torrent, it should point to a directory containing a directory with the same name as this torrent, and all the files of the torrent in it.
    • nodes

      public List<Pair<String,Integer>> nodes()
      Lists specified DHT nodes in the torrent (added with addNodes(List<Pair<String, Integer>>)). A node is a hostname and a port number where there is a DHT node running.
    • addNodes

      public TorrentBuilder addNodes(List<Pair<String,Integer>> value)
      This adds a DHT node to the torrent. This especially useful if you're creating a tracker less torrent. It can be used by clients to bootstrap their DHT node from. The node is a hostname and a port number where there is a DHT node running. You can have any number of DHT nodes in a torrent.
    • addNode

      public TorrentBuilder addNode(Pair<String,Integer> value)
      This adds a DHT node to the torrent. This especially useful if you're creating a tracker less torrent. It can be used by clients to bootstrap their DHT node from. The node is a hostname and a port number where there is a DHT node running. You can have any number of DHT nodes in a torrent.
    • trackers

      public List<Pair<String,Integer>> trackers()
    • addTrackers

      public TorrentBuilder addTrackers(List<Pair<String,Integer>> value)
      Adds a list of trackers to the torrent.
      See Also:
    • addTracker

      public TorrentBuilder addTracker(Pair<String,Integer> value)
      Adds a tracker to the torrent. This is not strictly required, but most torrents use a tracker as their main source of peers. The url should be a http:// or udp:// url to a machine running a bittorrent tracker that accepts announces for this torrent's info-hash. The tier is the fallback priority of the tracker. All trackers with tier 0 are tried first (in any order). If all fail, trackers with tier 1 are tried. If all of those fail, trackers with tier 2 are tried, and so on.
    • addTracker

      public TorrentBuilder addTracker(String url, int tier)
      Adds a tracker to the torrent. This is not strictly required, but most torrents use a tracker as their main source of peers. The url should be a http:// or udp:// url to a machine running a bittorrent tracker that accepts announces for this torrent's info-hash. The tier is the fallback priority of the tracker. All trackers with tier 0 are tried first (in any order). If all fail, trackers with tier 1 are tried. If all of those fail, trackers with tier 2 are tried, and so on.
    • addTracker

      public TorrentBuilder addTracker(String url)
      Adds a tracker on tier 0 to the torrent.
    • isPrivate

      public boolean isPrivate()
      Torrents with the private flag set ask clients to not use any other sources than the tracker for peers, and to not advertise itself publicly, apart from the tracker.
    • setPrivate

      public TorrentBuilder setPrivate(boolean value)
      Sets the private flag of the torrent.

      Torrents with the private flag set ask clients to not use any other sources than the tracker for peers, and to not advertise itself publicly, apart from the tracker.

    • similarTorrents

      public List<Sha1Hash> similarTorrents()
      See Also:
    • addSimilarTorrents

      public TorrentBuilder addSimilarTorrents(List<Sha1Hash> value)
      See Also:
    • addSimilarTorrent

      public TorrentBuilder addSimilarTorrent(Sha1Hash value)
      Add similar torrents (by info-hash).

      Similar torrents are expected to share some files with this torrent. Torrents sharing a collection name with this torrent are also expected to share files with this torrent. A torrent may have more than one collection and more than one similar torrents. For more information, see BEP 38.

      BEP 38: ...

    • collections

      public List<String> collections()
    • addCollections

      public TorrentBuilder addCollections(List<String> value)
    • addCollection

      public TorrentBuilder addCollection(String value)
      Add collections of similar torrents.

      Similar torrents are expected to share some files with this torrent. Torrents sharing a collection name with this torrent are also expected to share files with this torrent. A torrent may have more than one collection and more than one similar torrents. For more information, see BEP 38.

      BEP 38: ...

    • listener

      public TorrentBuilder.Listener listener()
    • listener

      public TorrentBuilder listener(TorrentBuilder.Listener value)
    • generate

      public TorrentBuilder.Result generate() throws IOException
      This function will generate a result with the .torrent file as a bencoded tree.
      Throws:
      IOException