【问题标题】:Android file exists() not workingAndroid文件存在()不起作用
【发布时间】:2018-12-02 22:10:18
【问题描述】:

现在我正在尝试制作从Uri 下载的文件,但我想制作它,以便如果文件已下载,它将无法再下载。所以我决定使用file.exists() 来做这件事,但是现在file.exists() 方法由于某种原因不起作用。

Uri uri = Uri.parse("http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf");

Uri path = Uri.parse("file:///storage/emulated/0/Download/");
String test = uri.getPath();
File file = new File(path.getPath());
File check = new File(path.getPath()+uri.getLastPathSegment());
if (!check.exists()||!check.isFile()) {
  DownloadManager.Request request = new DownloadManager.Request(uri);
  request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  request.setDestinationInExternalPublicDir(String.valueOf(file), uri.getLastPathSegment());
  Long reference = downloadManager.enqueue(request);
}
Intent intent = new Intent(MainActivity.this,ViewActivity.class);
intent.putExtra("book",""+uri.getLastPathSegment()+"");
startActivity(intent);

我尝试进行文件检查并查看文件是否存在,但我总是得到文件不存在,即使文件已经下载并位于正确的位置。有人可以帮我解决这个问题吗?

【问题讨论】:

  • isFile 如果不存在会返回 false
  • @cricket_007 我误解了这个问题...删除了我的答案
  • @alexander.egger 试过了,还是不行
  • 除了exists() 问题之外,您的方法很愚蠢。文件“x.foo”的存在并不意味着我下载了它,也没有完全下载它,也没有正确下载它。这只是意味着存在具有该名称的文件,这是完全不同的事情,您无法从有关文件来源或内容的事实中得出任何结论。

标签: java android


【解决方案1】:

if (!check.exists()||!check.isFile()) - 不好,因为从理论上讲,它可能会在名为 classes2.pdf 的文件夹上触发。所以,isFile() 就足够了。

确保您拥有 Manifest 中的所有权限

android.permission.WRITE_EXTERNAL_STORAGE

并且您在运行时也请求了读/写权限。

并通过

访问下载文件夹
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();

因为它可能是 emulated/0/Downloads 或可能不同,这取决于手机是否在访客模式下使用。

和名字

String name = Uri.parse("http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf").getLastPathSegment();`

然后进行检查

File check = new File(path, name);

【讨论】:

  • 试过了,即使文件存在,它仍然在下载
【解决方案2】:

代替:

request.setDestinationInExternalPublicDir(String.valueOf(file), uri.getLastPathSegment());

用途:

 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, uri
                    .getLastPathSegment());

原因:

setDestinationInExternalPublicDir 期望 dirType 作为您的第一个参数:

但是当它设置为String.valueOf(file)时,它会将文件存储在/storage/emulated/0/storage/emulated/0/Download/lesson2.pdf而不是storage/emulated/0/Download/。因此,您的条件总是失败。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-12
  • 2015-12-10
  • 2011-11-01
  • 1970-01-01
  • 2013-06-26
  • 2014-12-07
  • 2018-03-27
相关资源
最近更新 更多