android - pre-allocate space for a file before downloading it

坚强是说给别人听的谎言 提交于 2019-12-22 13:32:11

问题


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.


回答1:


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);
      }
  }


来源:https://stackoverflow.com/questions/9252332/android-pre-allocate-space-for-a-file-before-downloading-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!