2

如何在 android 上创建预分配文件?像稀疏文件一样的东西?

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

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

4

1 回答 1

3

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

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

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);
      }
  }
于 2012-06-08T21:02:03.190 回答