用Java修改.torrent文件

时间:2013-10-11 20:36:09

标签: java

我正在编写一个应用程序来下载torrent文件并修改它的跟踪链接(只需替换密码)。但可能我的编码有很大问题,因为当我保存修改后的文件时,它无法在我的torrent客户端中打开。

我写了一个代码来下载和修改文件:

@Override
public void exeucte(String link) throws IOException {
    FileOutputStream fos = null;
    try {
        URL website = new URL(link);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        String fileName = getFileName(link);
        fos = new FileOutputStream(fileName);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        replacePassKey(fileName);
    } finally {
        if (fos != null)
            fos.close();
    }

}

private void replacePassKey(String fileName) throws IOException {
    File originalFile = new File(fileName);
    String lines = readLines(originalFile);
    String replacedLines = lines.replaceAll("(.*passkey=)(.*)(:comment27.*)", "$1" + PASS_KEY + "$3");
    originalFile.delete();
    writeReplacedLines(replacedLines, originalFile);
}

private void writeReplacedLines(String replacedLines, File file) throws IOException {
    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(file));
        bw.write(replacedLines);
    } finally {
        if (bw != null)
            bw.close();
    }

}

private String readLines(File originalFile) throws IOException {
    RandomAccessFile raf = null;
    String lines = null;
    try {
        raf = new RandomAccessFile(originalFile, "r");
        byte[] bytes = new byte[(int) raf.length()];
        raf.read(bytes);
        lines = new String(bytes, Charset.forName("UTF8"));
    } finally {
        if (raf != null)
            raf.close();
    }
    return lines;
}

我确信下载有效,因为我可以在torrent客户端中打开未修改的文件(当我在KomodoEdit中修改下载的文件时)。但是当我修改文件并保存替换的String时,我的客户端无法打开它并抱怨无效数据。

任何人都有任何想法?也许UTF8错了或者我必须更改我的代码的某些部分?

1 个答案:

答案 0 :(得分:0)

尝试使用各种设置打开它,然后选中the wiki page