在Java中,当需要解析BT种子文件(Torrent)时,一种方案是使用Eclipse ECF中的org.eclipse.bittorrent。
Torrent是一个使用BEncoding的Dictionary,具体可以查看BEP的相关文档(BEP0003),在此不再赘述。org.eclipse.bittorrent的使用非常简单,但由于其出现的年代已经比较久远,因此其缺点之一就在于解析的是一个Torrent文件的Metadata(参见BEP0009中的metadata一节),即the info-dictionary part of the .torrent file,而没有解析诸如announce等字段。
1、org.eclipse.bittorrent的文档
org.eclipse.bittorrent是Eclipse ECF中的一个插件(这个ECF好像历史也比较久远了),在Elipse官网上可以找到org.eclipse.bittorrent的官方文档。我们所关注的主要是类
org.eclipse.ecf.protocol.bittorrent.TorrentFile,其方法主要包括:
Method Summary | |
---|---|
boolean |
equals(java.lang.Object other) Returns whether this TorrentFile is equal to the given object. |
java.lang.String[] |
getFilenames() Retrieves the names of all of the files’ that is specified by this Torrent . |
java.lang.String |
getHexHash() Returns the hexadecimal representation of the hash returned from getInfoHash() . |
java.lang.String |
getInfoHash() Returns the hash of the info dictionary specified by the torrent’s metainfo. |
long[] |
getLengths() Retrieve the specified lengths of the files contained within this torrent. |
java.lang.String |
getName() Retrieves the name of this torrent file. |
int |
getNumPieces() Returns the number of pieces associated with this torrent. |
int |
getPieceLength() Returns the length of a piece. |
java.lang.String[] |
getPieces() Returns a string array that contains the SHA-1 hash of each of the pieces defined by the torrent’s metainfo. |
java.io.File |
getTargetFile() Gets the file that has been set as the target file of this torrent per setTargetFile(File) . |
long |
getTotalLength() Retrieves the total length of all of the files specified within this torrent. |
java.lang.String |
getTracker() Retrieves the URL of the tracker that’s handling the requests for this torrent. |
int |
hashCode() Returns the hash code of this TorrentFile based on its info hash. |
boolean |
isMultiFile() Returns whether this torrent is associated with multiple files or not. |
void |
save(java.io.File file) Writes the contents of the file that was used to initialize this TorrentFile onto the provided file. |
void |
setTargetFile(java.io.File file) Sets the target file or folder that this torrent should download to or look for the corresponding files in. |
boolean |
validate() Checks the integrity of the target file or folder as set by setTargetFile(File) to determine whether its contents pass all of the hash checks. |
2、获取org.eclipse.bittorrent
我们可以从Maven中央仓库上获取org.eclipse.bittorrent,Maven中央仓库上org.eclipse.bittorrent只有一个版本,链接为:http://mvnrepository.com/artifact/org.eclipse/bittorrent。
在POM中可以直接使用如下的依赖:
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>bittorrent</artifactId>
<version>0.3.0-v20070627-1030</version>
</dependency>
3、使用org.eclipse.bittorrent
我们可以使用如下的代码来解析Torrent文件:
其输出形如:
请注意,当Torrent中没有指定编码方式时,默认编码方式为ISO-88559-1,因此当涉及中文时需要进行转码,否则文件名会是乱码。对于有文件夹层级结构的也没有问题,输出的结果与迅雷解析的结果一致:
转载时请保留出处,违法转载追究到底:进城务工人员小梅 » 使用Java解析Torrent文件(BT种子),基于使用Eclipse ECF中的org.eclipse.bittorrent方案