gpt4 book ai didi

安卓棉花糖 : Files written by SAF are not immediatelly written

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:01 28 4
gpt4 key购买 nike

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

当我使用例如:

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 秒。

最佳答案

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

context.getContentResolver().getOutputStream(someUri))

延迟 10 秒。它也延迟删除。 IE。当你尝试时:

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 类进行只读操作,因为它速度更快。但自 Marshmallow 以来,我不能将它与 SAF 一起使用。它必须严格使用 SAF api:

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

关于安卓棉花糖 : Files written by SAF are not immediatelly written,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800564/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com