0

I need to create an empty binary file with given size in java. What is the fastest way to do this? I also need to update UI simultaneously. I use following code to do this. But it’s not very fast. Can everyone help me? Tnx

public static void create(String pathAndName, int fileSize) {
    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(pathAndName);
      int length = 10 * 1024;
      byte[] buffer = new byte[length];
      int len = buffer.length;
      int createdSize = 0;

      int percent = 0;
      int lastPercent = 0;

      while (createdSize < fileSize) {
        createdSize += length;
        if (createdSize > fileSize) {
          len = fileSize - (createdSize - length);
        }
        lastPercent = percent;
        percent = (int) (((double) createdsize / fileSize) * 100);
        if(lastPercent != percent){
          updateUI(percent);
        }
        fileOutputStream.write(buffer, 0, len);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    if (fileOutputStream != null) {
      try {
        fileOutputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Hadi
  • 544
  • 1
  • 8
  • 28
  • In that solution, the new file does not occupy memory!! – Hadi Dec 07 '17 at 12:54
  • 1
    That is called sparse file. https://en.wikipedia.org/wiki/Sparse_file – ThomasEdwin Dec 07 '17 at 12:55
  • I did not have information about those files. thank you my friend): – Hadi Dec 07 '17 at 13:02
  • 1
    Beware, a sparse may not be what you need. When you need to create a file with a given size, it is often because you want to be sure that everything has been allocated at creation time, and not other allocation will later be required. A sparse file will **not** guarantee that... – Serge Ballesta Dec 07 '17 at 13:04
  • I'll remember that. thank you. – Hadi Dec 07 '17 at 13:19

0 Answers0