java创建指定大小的文件

有一种应用场景就是文件的断点续传或多线程传输文件,在传文件之前先要建一个和目标文件大小一致的文件空白文件(里面数据都是0)这样下载或做其他操作时只要seek到具体文件位置即可。

  1. import java.io.File;   
  2. import java.io.FileOutputStream;   
  3. import java.io.IOException;   
  4. import java.io.Writer;   
  5. import java.nio.ByteBuffer;   
  6. import java.nio.channels.FileChannel;   
  7.   
  8. public static long KBSIZE = 1024;   
  9. public static long MBSIZE1 = 1024 * 1024;   
  10. public static long MBSIZE10 = 1024 * 1024 * 10;   
  11.   
  12. public static boolean createFile(File file, long fileLength) {   
  13.     FileOutputStream fos = null;   
  14.     try {   
  15.   
  16.         if (!file.exists()) {   
  17.         file.createNewFile();   
  18.         }   
  19.   
  20.         long batchSize = 0;   
  21.         batchSize = fileLength;   
  22.         if (fileLength > KBSIZE) {   
  23.         batchSize = KBSIZE;   
  24.         }   
  25.         if (fileLength > MBSIZE1) {   
  26.         batchSize = MBSIZE1;   
  27.         }   
  28.         if (fileLength > MBSIZE10) {   
  29.         batchSize = MBSIZE10;   
  30.         }   
  31.         long count = fileLength / batchSize;   
  32.         long last = fileLength % batchSize;   
  33.   
  34.         fos = new FileOutputStream(file);   
  35.         FileChannel fileChannel = fos.getChannel();   
  36.         for (int i = 0; i < count; i++) {   
  37.         ByteBuffer buffer = ByteBuffer.allocate((int) batchSize);   
  38.         fileChannel.write(buffer);   
  39.         }   
  40.         ByteBuffer buffer = ByteBuffer.allocate((int) last);   
  41.         fileChannel.write(buffer);   
  42.         fos.close();   
  43.         return true;   
  44.     } catch (IOException e) {   
  45.         e.printStackTrace();   
  46.     } finally {   
  47.         try {   
  48.         if (fos != null) {   
  49.             fos.close();   
  50.         }   
  51.         } catch (IOException e) {   
  52.         e.printStackTrace();   
  53.         }   
  54.     }   
  55.     return false;   
  56. }   
  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓