DownloadManager - 如果文件已存在,则重命名下载

时间:2012-08-24 16:18:04

标签: android file rename exists

public void onClick(DialogInterface dialog, int id) {

    Uri u = Uri.parse(url);
    File f = new File("" + u);

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setTitle("");
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, f.getName());

    // just my bullshit here please correct here                    
    if (f.exists()) {
        File sdcard = Environment.getExternalStorageDirectory();
        File from = new File(sdcard,f.getName());
        File to = new File(sdcard,"*"+f.getName());
        from.renameTo(to);
    }

    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);

                    }

我有这个小代码然后点击它从网址下载文件但是当文件已经下载并且具有相同的名称它只显示失败时,我如何检查文件是否已经存在并让DownloadManager下载该文件不同的名字?

1 个答案:

答案 0 :(得分:1)

DownloadManager默认情况下会重命名文件。它会在文件名的末尾添加-[NUMBER]

所以hello.jpg转向hello-1.jpg

也许看看this example。我用它并且它有效。