Question

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.

Was it helpful?

Solution

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);
      }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top