在java中创建空二进制文件的最快方法是什么?

时间:2017-12-07 12:46:49

标签: java file-io

我需要在java中创建一个给定大小的空二进制文件。最快的方法是什么?我还需要同时更新UI。我使用以下代码来执行此操作。但它不是很快。大家能帮帮我吗? 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();
      }
    }
  }

0 个答案:

没有答案