我想检查Android中的“下载”文件夹中是否已存在该文件。我使用Android下载管理器下载文件。在那里if
部分不起作用。如果文件已存在(例如:文件名 - songname.mp3),则第二次下载同一文件时,它会将文件下载为songname1.mp3
。我试过下面的代码。如果文件已经存在,我想显示一条消息。
请帮我解决这个问题。
public void DownloadChecker() {
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
} else {
String servicestring = Context.DOWNLOAD_SERVICE;
DownloadManager downloadmanager;
downloadmanager = (DownloadManager) getSystemService(servicestring);
Uri uri = Uri.parse(DownloadUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalFilesDir(MainActivity.this,
Environment.DIRECTORY_DOWNLOADS,"mysongs.mp3");
Long reference = downloadmanager.enqueue(request);
}
}
答案 0 :(得分:1)
您应该尝试更改:
File applictionFile = new File(Environment.
getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS)+ "/"+"mysongs.mp3");
为:
File applictionFile = new File(Environment.
getExternalStoragePublicDirectory(Environment
.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + "mysongs.mp3");
答案 1 :(得分:1)
您在哪个测试设备上测试您的应用?它是否在api-23之上,那么你应该在运行时设置权限!或者试试这个
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/mysongs.mp3");
if(myFile.exists()){
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
答案 2 :(得分:1)
更改
if(applictionFile.exists()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
以强>
if(applictionFile.canRead()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
或强>
if(applictionFile.isFile()) {
Toast.makeText(getApplicationContext(), "File Already Exists",
Toast.LENGTH_LONG).show();
}
答案 3 :(得分:1)
以简单的方式尝试
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do your code stuff
}