2013-10-11 48 views
2

我正在編寫一個應用程序來下載torrent文件並修改它的跟蹤鏈接(只需更換密碼)。但是,可能我對編碼有很大的問題,因爲當我保存修改後的文件時,它不能在我的torrent客戶端打開。修改Java中的.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下載文件)打開不修改的文件。但是,當我修改文件並保存替換字符串我的客戶端無法打開它並抱怨無效的數據。

任何人有任何想法?也許UTF8是錯誤的,或者我必須更改我的代碼的一部分?

+0

我猜這個文件應該是ASCII碼或者是一個變體。所以UTF-8的直接輸出不適合。 –

+0

有沒有辦法檢查下載的文件的編碼?在wiki上有關於torrent文件中UTF-8的信息。 –

+0

我的電腦上的torrent文件顯示爲ANSI ... Source - 用Windows記事本打開並嘗試另存爲。在底部它顯示在下拉框中檢測到的編碼。 –

回答

0

嘗試用各種設置打開它並檢查the wiki page

+0

請注意,[僅限鏈接的答案](http://meta.stackoverflow.com/tags/link-only-answers/信息),所以SO答案應該是搜索解決方案的終點(而另一個引用的中途停留時間往往會隨着時間的推移而變得陳舊)。請考慮在此添加獨立的摘要,並將鏈接保留爲參考。 – kleopatra