首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android : SAF编写的文件不是立即编写的

Android : SAF编写的文件不是立即编写的
EN

Stack Overflow用户
提问于 2016-03-04 16:03:50
回答 1查看 885关注 0票数 4

我使用SAF (存储访问框架)将文件写入SD卡。在Marshmallow上,文件实际上是以很大的延迟(大约10秒)编写和更新的。

当我使用例如:

代码语言:javascript
复制
android.support.v4.provider.DocumentFile docFile = DocumentFile.fromTreeUri(context, getUri()) // tree uri that represents some existing file on sd card
File file = getFile(getUri()); // java.io.File that points to same file as docFile

docFile.length(); // length of current file is e.g. 150B
file.length(); // length of file is also 150B
try (OutputStream outStream = context.getContentResolver().getOutputStream(docFile.getUri()))
{
   outStream.write(data, 0, 50); // overwrite with 50 B
   outStream.flush(); // didn't help
}

docFile.length(); // it still returns 150B !!
file.length(); // it still returns 150B

Thread.sleep(12000); // sleep 12 seconds

docFile.length(); // now it returns  correctly 50B
file.length(); // now it returns  correctly 50B

顺便说一句。当我使用File.length()方法检查长度时,它返回相同的值。

有办法马上写吗?或者我能给你安排个听众吗?否则我必须定期检查尺寸,我不想这样做。事实上,我不想在文件写完之后等10秒。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-05 09:37:47

因此,我发现,当我同时使用java.io.File和SAF时,会出现延迟。通过方法File.isDirectory()File.exists()File.length()检查文件会导致后续调用

代码语言:javascript
复制
context.getContentResolver().getOutputStream(someUri))

会延迟10秒。它也延迟了删除。也就是说,当你尝试:

代码语言:javascript
复制
DocumentFile docFile = DocumentFile.fromTreeUri(context, someUri);
File file = new File("path to same file as someUri");
if(file.exists() && !file.isDirectory()) // this cause the delay
{
  docFile.delete();
}

boolean exists = file.exists(); // exists is INCORRECTLY true
exists = docFile.exists(); // exists is INCORRECTLY true

Thread.sleep(12000);

exists = file.exists(); // exists is CORRECTLY false
exists = docFile.exists(); // exists is CORRECTLY false

我使用File类进行只读操作,因为它更快。但我不能和苏丹武装部队一起使用,因为马斯马洛。它必须严格使用SAF api:

代码语言:javascript
复制
DocumentFile docFile = DocumentFile.fromTreeUri(context, someUri);
if(docFile.exists() && !docFile.isDirectory()) // this cause the delay
{
  docFile.delete();
}

boolean exists = docFile.exists(); // exists is CORRECTLY false
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35800564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档