2012-07-20 18 views
20

URLからePubファイルをダウンロードしています。ファイルをダウンロードする前にURLからファイル名を解析します。

は、今私は、ユーザーが同じファイルを再ダウンロードしようとするとするメカニズムを実装したい、彼は警告/エラーメッセージとを再度ダウンロードしてはならない、そのファイルを取得する必要があります。

これを実装するには、ライブラリにあるファイルの名前を、ダウンロードしようとしているファイルの名前で確認する必要があります。

しかし、ちょうどthis download linkがあり、ファイル名ではありません。

ファイルを既存のファイルと比較するためにダウンロードする前にファイル名を取得するにはどうすればよいですか?

あなたが the guessFileName() methodを使用することができますアンドロイドで

答えて

46

URLUtil.guessFileName(url, null, null) 

また、Javaで単純な解決策が考えられます。

String fileName = url.substring(url.lastIndexOf('/') + 1); 

(あなたのURLを仮定すると、次の形式になります。http://xxxxxxxxxxxxx/filename.ext

+0

は、私が本のコレクションが含まれているリンクがあると(例えばのために。 'www.bookstore.com')、私は一冊の本(URLと' www.bookstoreを選択し、そこから。 com/book1.epub')をダウンロードしてください。 **特定の本のURLを取得するにはどうすればいいですか?つまり、「www.bookstore.com/book1.epub」ですか? 'webView.getUrl()'は、最初のロードを除いて、まったく起動されません。 – GAMA

+2

あなたの解決策は、params(?param = value)もanchor(#anchor)もない場合にのみ機能します。 –

2

あなたは実際にファイル名を比較する必要はありません。 ファイル絶対パスのファイルのオブジェクトを作成し、ファイルが存在するかどうかを確認してください。

protected boolean need2Download(String fileName) { 

    File basePath = new File(BOOK_STORE_PATH); 

    File fullPath = new File(basePath, fileName); 

    if (fullPath.exists()) 
     return false; 
    return true; 
} 

protected void downloadFile(String url) { 
    String fileName = url.substring(url.lastIndexOf('/') + 1); 

    if (need2Download(fileName)) { 
     // download 
    } 
} 
4

それをシンプルに保つ:私は物事を単純化すべきURLの#のある、getPath()を使用して思う

/** 
* This function will take an URL as input and return the file name. 
* <p>Examples :</p> 
* <ul> 
* <li>http://example.com/a/b/c/test.txt -> test.txt</li> 
* <li>http://example.com/ -> an empty string </li> 
* <li>http://example.com/test.txt?param=value -> test.txt</li> 
* <li>http://example.com/test.txt#anchor -> test.txt</li> 
* </ul> 
* 
* @param url The input URL 
* @return The URL file name 
*/ 
public static String getFileNameFromUrl(URL url) { 

    String urlString = url.getFile(); 

    return urlString.substring(urlString.lastIndexOf('/') + 1).split("\\?")[0].split("#")[0]; 
} 
1

public static String getFileNameFromUrl(URL url) { 

    String urlPath = url.getPath(); 

    return urlPath.substring(urlPath.lastIndexOf('/') + 1); 
} 

を参照してください、http://developer.android.com/reference/java/net/URL.html#getPath()

+0

私はそれを使用しますが、単純化するものではありません。getPath()を使用すると、httt://domain.com/file.ext?a = 1#anchorのようなクエリパラメータを持つURLを処理できます。 @TimAutinは私にとってもっと読みやすいですが。 – Davide

関連する問題