android - 在下载文件之前预先为其分配空间

发布于 01-05 01:13 字数 266 浏览 3 评论 0原文

如何在 Android 上创建预分配文件?像稀疏文件之类的东西?

我需要制作一个将下载大文件的应用程序,并且我想避免在下载开始时出现空间不足的错误。我的解决方案需要支持恢复和写入内部和外部存储。

我已经尝试过这里写的内容: 在 Java 中创建给定大小的文件 但由于某种原因,这些解决方案都不起作用。

how can i create a pre-allocated file on android? something like a sparse file ?

i need to make an applicaton that will download a large file , and i want to avoid having an out-of-space error while the download is commencing . my solution needs to support resuming and writing to both internal and external storage.

i've tried what is written here:
Create file with given size in Java
but for some reason, none of those solutions worked.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梓梦2025-01-12 01:13:26

这很奇怪。
现在工作正常了。也许我以错误的方式测试了它。

对于那些有问题的人来说,这是一个工作代码:

final String path=getFilesDir().getParent()+"/t.txt";
RandomAccessFile newSparseFile=null;
try
  {
  new File(path).delete();
  newSparseFile=new RandomAccessFile(path,"rw");
  // create a 1MB file:
  newSparseFile.setLength(1024*1024);
  }
catch(final Exception e)
  {
  Log.e("DEBUG","error while creating file:"+e);
  }
finally
  {
  if(newSparseFile!=null)
    try
      {
      newSparseFile.close();
      Log.d("DEBUG","length:"+new File(path).length());
      }
    catch(final IOException e)
      {
      Log.e("DEBUG","error while closing file:"+e);
      }
  }

this is odd.
it works fine now . perhaps i've tested it in a wrong way.

here's a working code , for those who have problems with it :

final String path=getFilesDir().getParent()+"/t.txt";
RandomAccessFile newSparseFile=null;
try
  {
  new File(path).delete();
  newSparseFile=new RandomAccessFile(path,"rw");
  // create a 1MB file:
  newSparseFile.setLength(1024*1024);
  }
catch(final Exception e)
  {
  Log.e("DEBUG","error while creating file:"+e);
  }
finally
  {
  if(newSparseFile!=null)
    try
      {
      newSparseFile.close();
      Log.d("DEBUG","length:"+new File(path).length());
      }
    catch(final IOException e)
      {
      Log.e("DEBUG","error while closing file:"+e);
      }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文