在我的下载管理器下载文件之前,如何在文件名中用“_”和“/”符号替换“+”符号?
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
答案 0 :(得分:2)
让我们假设你的字符串/文件名是:
String myFileName = "basal_metabolic_rate+example.pdf";
您可以执行以下操作,将+
替换为_
:
String result = myFileName.replaceAll("[+]", "_");
字符串result
现在将返回:
basal_metabolic_rate_example.pdf
当你想用“=”代替“/”时,你也可以这样做:
String myFileName = "basal/metabolic/rate/example.pdf";
String result = myFileName.replaceAll("[/]", "=");
// Your file will now be basal=metabolic=rate=example.pdf
修改强>
以下是在代码中实现它的方法:
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
//You can first get the filename:
String filename = URLUtil.guessFileName(url, contentDisposition, mimeType);
//Then you can replace the "+" with "_"
String replacePlus = filename.replaceAll("[+]", "_");
//Then you can replace the "/" with "="
String replaceSlash = replacePlus.replaceAll("[/]", "=");
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
//Now here where you set the title you can set it to the last edited string, like this:
request.setTitle(replaceSlash);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//And here where you set the destination directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, replaceSlash);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);