/**
   * Writes the Item's creation date to the Items Random Access File
   *
   * @param file - the Item's Random Access File
   */
  private void writeCreationDate(RandomAccessFile file) {
    try {
      file.writeShort(getCreationDate().get(Calendar.YEAR));
      file.writeByte(getCreationDate().get(Calendar.MONTH));
      file.writeByte(getCreationDate().get(Calendar.DAY_OF_MONTH));
    } catch (Exception e) {

    }
  }
  /**
   * Writes the Item location to the Items Random Access File
   *
   * @param file - the Item's Random Access File
   */
  private void writeLocationToFile(RandomAccessFile file) {
    try {
      file.writeByte(1); // Write the warehouse number
      file.writeByte(getLocation().getAisle()); // Write the aisle number
      file.writeByte(getLocation().getColumn()); // Write the column number
      file.writeChar(getLocation().getRow()); // Write the row number
    } catch (Exception e) {

    }
  }
示例#3
0
  public int getOrCreateField(Field f) throws IOException, ReflectiveOperationException {
    if (fieldIdMapping.size() > f.getFieldId()) {
      return fieldIdMapping.get(f.getFieldId()).getFieldId();
    }
    RandomAccessFile file = null;
    try {
      file = new RandomAccessFile(filePath, "rw");
      file.seek(file.length());
      f.setFieldId(fieldIdMapping.size());
      file.writeUTF(f.getFieldName());
      int typeId = fieldTypeStore.getOrCreateTypeId(f.getFieldType());
      file.writeByte(typeId);
      BitSet bitSet = new BitSet(8);
      bitSet.set(BIT_INDEX_INDEXED, f.isIndexed());
      bitSet.set(BIT_INDEX_STORED, f.isStored());
      file.write(bitSet.toByteArray());
      // Add to indexes
      fieldIdMapping.add(f);
      fieldNameMapping.put(f.getFieldName(), f);

      return f.getFieldId();
    } finally {
      if (file != null) {
        file.close();
      }
    }
  }
示例#4
0
文件: FileL.java 项目: lzs0420/mytest
 /**
  * @param skip 跳过多少过字节进行插入数据
  * @param str 要插入的字符串
  * @param fileName 文件路径
  */
 public static void writeSkip(long skip, String str, String fileName) throws IOException {
   RandomAccessFile raf = null;
   try {
     raf = new RandomAccessFile(fileName, "rw");
     if (skip < 0 || skip > raf.length()) {
       System.out.println("跳过字节数无效");
       return;
     }
     byte[] b = str.getBytes();
     raf.setLength(raf.length() + b.length);
     for (long i = raf.length() - 1; i > b.length + skip - 1; i--) {
       raf.seek(i - b.length);
       byte temp = raf.readByte();
       raf.seek(i);
       raf.writeByte(temp);
     }
     raf.seek(skip);
     raf.write(b);
   } catch (Exception e) {
     throw new IOException(e);
   } finally {
     try {
       raf.close();
     } catch (IOException e) {
       throw e;
     }
   }
 }
示例#5
0
 public void saveMetaData() throws IOException {
   pageFile.seek(offset);
   pageFile.writeInt(nextPageId);
   pageFile.writeInt(currentFill);
   pageFile.writeInt(bloomfilter);
   pageFile.writeByte(type);
 }
 /* write a chunk data to the region file at specified sector number */
 private void write(int sectorNumber, byte[] data, int length) throws IOException {
   debugln(" " + sectorNumber);
   file.seek(sectorNumber * SECTOR_BYTES);
   file.writeInt(length + 1); // chunk length
   file.writeByte(VERSION_DEFLATE); // chunk version number
   file.write(data, 0, length); // chunk data
 }
示例#7
0
 // see DbFile.java for javadocs
 public void writePage(Page page) throws IOException {
   // some code goes here
   long offset = page.getId().pageNumber() * BufferPool.PAGE_SIZE;
   byte[] data = page.getPageData();
   try {
     raf.seek(offset);
     for (int i = 0; i < data.length; i++) {
       raf.writeByte(data[i]);
     }
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }
 /**
  * Corrupt the specified file. Some random bytes within the file will be changed to some random
  * values.
  *
  * @throws IllegalArgumentException if the given file is not a file
  * @throws IOException if an IOException occurs while reading or writing the file
  */
 public static void corruptFile(File file) throws IOException {
   if (!file.isFile()) {
     throw new IllegalArgumentException("Given argument is not a file:" + file);
   }
   RandomAccessFile raf = new RandomAccessFile(file, "rws");
   Random random = new Random();
   for (long i = 0; i < raf.length(); i++) {
     raf.seek(i);
     if (random.nextBoolean()) {
       raf.writeByte(random.nextInt());
     }
   }
   raf.close();
 }
示例#9
0
  public void commitChanges() throws IOException, RuntimeException {
    Throwable t = null;
    RandomAccessFile dataFile = null;
    try {
      try {
        dataFile = new RandomAccessFile(filePath, "rw");
      } catch (FileNotFoundException e) {
        throw new RuntimeException(filePath + " can't get access to file", e);
      }
      if (data == null || data.isEmpty()) {
        closeDataFile(dataFile);
        Shell sh = new Shell(tablePath, false);
        if (sh.rm(filePath) != Shell.ExitCode.OK) {
          throw new RuntimeException(filePath + " can't delete file");
        }
        exists = false;
        return;
      }

      int offset = 0;
      Set<Map.Entry<String, Storeable>> mySet = data.entrySet();
      for (Map.Entry<String, Storeable> myEntry : mySet) {
        offset += getLength(myEntry.getKey()) + 1 + 4;
      }
      int currOffset = offset;
      dataFile.setLength(0);
      dataFile.seek(0);
      for (Map.Entry<String, Storeable> myEntry : mySet) {
        dataFile.write(myEntry.getKey().getBytes());
        dataFile.writeByte(0);
        dataFile.writeInt(currOffset);
        currOffset += getLength(table.getProvider().serialize(table, myEntry.getValue()));
      }
      for (Map.Entry<String, Storeable> myEntry : mySet) {
        dataFile.write(table.getProvider().serialize(table, myEntry.getValue()).getBytes());
      }
    } catch (RuntimeException e5) {
      t = e5;
      throw e5;
    } finally {
      try {
        closeDataFile(dataFile);
      } catch (Throwable e6) {
        if (t != null) {
          t.addSuppressed(e6);
        }
      }
    }
  }
示例#10
0
 private static void MAPPER_SaveBinds() {
   String fileName = JavaMapper.mapperfile;
   try {
     RandomAccessFile saveFile = new RandomAccessFile(fileName, "rw");
     for (CEvent event : events) {
       saveFile.write(event.GetName().getBytes());
       for (CBind bind : event.bindlist) {
         String buf = " \"" + bind.ConfigName() + bind.AddFlags() + "\"";
         saveFile.write(buf.getBytes());
       }
       saveFile.writeByte((byte) '\n');
     }
     saveFile.close();
     // change_action_text("Mapper file saved.",CLR_WHITE);
   } catch (Exception e) {
     Log.log_msg("Can't open " + fileName + " for saving the mappings");
   }
 }
示例#11
0
  /**
   * Writes the initial data chunks that start the wave file. Prepares file for data samples to
   * written.
   *
   * @param comment ignored by the WAV header.
   * @exception IOException
   */
  public void writeHeader(final String comment) throws IOException {
    /* writes the RIFF chunk indicating wave format */
    byte[] chkid = "RIFF".getBytes();
    raf.write(chkid, 0, chkid.length);
    writeInt(raf, 0); /* total length must be blank */
    chkid = "WAVE".getBytes();
    raf.write(chkid, 0, chkid.length);

    /* format subchunk: of size 16 */
    chkid = "fmt ".getBytes();
    raf.write(chkid, 0, chkid.length);
    if (isPCM) {
      writeInt(raf, 16); // Size of format chunk
      writeShort(raf, WAVE_FORMAT_PCM); // Format tag: PCM
      writeShort(raf, (short) channels); // Number of channels
      writeInt(raf, sampleRate); // Sampling frequency
      writeInt(raf, sampleRate * channels * 2); // Average bytes per second
      writeShort(raf, (short) (channels * 2)); // Blocksize of data
      writeShort(raf, (short) 16); // Bits per sample
    } else {
      int length = comment.length();
      writeInt(raf, (short) (18 + 2 + 80 + length)); // Size of format chunk
      writeShort(raf, WAVE_FORMAT_SPEEX); // Format tag: Speex
      writeShort(raf, (short) channels); // Number of channels
      writeInt(raf, sampleRate); // Sampling frequency
      writeInt(
          raf,
          (calculateEffectiveBitrate(mode, channels, quality) + 7)
              >> 3); // Average bytes per second
      writeShort(raf, (short) calculateBlockSize(mode, channels, quality)); // Blocksize of data
      writeShort(raf, (short) quality); // Bits per sample
      writeShort(raf, (short) (2 + 80 + length)); // The count in bytes of the extra size
      raf.writeByte(0xff & 1); // ACM major version number
      raf.writeByte(0xff & 0); // ACM minor version number
      raf.write(buildSpeexHeader(sampleRate, mode, channels, vbr, nframes));
      raf.writeBytes(comment);
    }

    /* write the start of data chunk */
    chkid = "data".getBytes();
    raf.write(chkid, 0, chkid.length);
    writeInt(raf, 0);
  }
  /** write the first 32 bytes to file */
  public void write(RandomAccessFile ff) throws tinySQLException {
    try {
      // -----------------------------
      // write out the primary header
      ff.seek(FLAG_INDEX);
      ff.writeByte((byte) 0x03);

      setTimestamp(ff); // set current date YY MM DD (dBase is not Y2K save)

      setNumRecords(ff, 0);

      setHeaderLength(ff, numFields);

      setRecordLength(ff, recordLength);

      setReserved(ff);

    } catch (Exception e) {
      throw new tinySQLException(e.getMessage());
    }
  }
示例#13
0
文件: asm.java 项目: naxIO/nabaztag
  private static void writeFile(String sFile, byte[] bytes) {
    byte[] emptybuf = null;

    try {
      RandomAccessFile file = new RandomAccessFile(new File(sFile), "rw");

      file.seek(file.length()); // append

      int i = 0;

      for (i = 0; i < bytes.length; i++) {
        file.writeByte(bytes[i]);
      }

      log("Wrote " + i + " bytes to " + sFile);
      file.close();
      return;
    } catch (IOException es) {
      log("File not found.");
    }

    return;
  }
示例#14
0
  public void export_song_to_file(int a_slot, String a_file_path) {
    if (a_slot < 0 || a_slot > 0x1f) {
      return;
    }
    RandomAccessFile m_file = null;
    try {
      m_file = new RandomAccessFile(a_file_path, "rw");

      int l_file_name_ptr = g_file_name_start_ptr + a_slot * g_file_name_length;
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr++]);
      m_file.writeByte(m_work_ram[l_file_name_ptr]);

      int l_file_version_ptr = g_file_version_start_ptr + a_slot;
      m_file.writeByte(m_work_ram[l_file_version_ptr]);

      int l_block_id = 0;
      int l_block_alloc_table_ptr = g_block_alloc_table_start_ptr;

      while (l_block_id < getTotalBlockCount()) {
        if (a_slot == m_work_ram[l_block_alloc_table_ptr++]) {
          int l_block_ptr = g_block_start_ptr + l_block_id * g_block_size;
          for (int l_byte_index = 0; l_byte_index < g_block_size; l_byte_index++) {
            m_file.writeByte(m_work_ram[l_block_ptr++]);
          }
        }
        l_block_id++;
      }
      m_file.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#15
0
  public static void main(String[] argv) {

    String victim = "Beginner"; // What's the name of the target?
    int fpointer = 0; // Where are we in the target class file?

    // How on earth do I use this thing?
    if (argv.length != 0) {
      System.out.println("Try \"java Attacker" + "\".");
      System.exit(1);
    }

    // If the target isn't writeable, then forget the whole deal.
    File testit = new File(victim + ".class");
    if (!(testit.canWrite())) {
      System.out.println(victim + ".class must be writeable.  Fix it!");
      System.exit(2);
    }
    try {
      RandomAccessFile target = new RandomAccessFile(victim + ".class", "rw");

      /* Adjust the proper attribute_length and code_length in order to maintain
      the hacked class file's verifiability. */

      // Increase the attacked method's attribute_lenth by 3.
      fpointer = 455;
      target.seek(fpointer);
      int changed_byte = (int) target.readUnsignedByte() + 3;
      target.seek(fpointer);
      target.writeByte(changed_byte);

      // Increase the attacked method's code_length by 3.
      fpointer = 463;
      target.seek(fpointer);
      changed_byte = (int) target.readUnsignedByte() + 3;
      target.seek(fpointer);
      target.writeByte(changed_byte);

      /* Insert the 3 bytes of code to make Beginner.class deviant */

      // Get to where we want to insert code.
      fpointer = 506;
      target.seek(fpointer);

      // Save the remainder of the target class file.
      int diff = (int) target.length() - fpointer;
      byte[] tail = new byte[diff];
      target.read(tail, 0, diff);

      // Insert the 3 bytes.
      target.seek(fpointer);
      target.writeByte(167);
      target.writeByte(255);
      target.writeByte(214);

      // Restore the tail.
      target.write(tail);

      // All the changes are made, so close the file and get out of here
      target.close();
    } catch (IOException ioe) {
    }
  }
示例#16
0
  private boolean writeIndex() {
    boolean ret = false;
    if (readFromIndex || !usePreindexedCache) {
      return true;
    }

    if (!writeIndex) {
      return true;
    }

    File indexFile = getIndexFile();
    if (indexFile == null) {
      return false;
    }

    RandomAccessFile raf = null;
    long writtenSoFar = 0;
    try {
      raf = new RandomAccessFile(indexFile, "rw");

      raf.writeLong(zipFileLastModified);
      writtenSoFar += 8;

      List<DirectoryEntry> directoriesToWrite = new ArrayList<DirectoryEntry>();
      Map<RelativeDirectory, Long> offsets = new HashMap<RelativeDirectory, Long>();
      raf.writeInt(directories.keySet().size());
      writtenSoFar += 4;

      for (RelativeDirectory dirName : directories.keySet()) {
        DirectoryEntry dirEntry = directories.get(dirName);

        directoriesToWrite.add(dirEntry);

        // Write the dir name bytes
        byte[] dirNameBytes = dirName.getPath().getBytes("UTF-8");
        int dirNameBytesLen = dirNameBytes.length;
        raf.writeInt(dirNameBytesLen);
        writtenSoFar += 4;

        raf.write(dirNameBytes);
        writtenSoFar += dirNameBytesLen;

        // Write the number of files in the dir
        List<Entry> dirEntries = dirEntry.getEntriesAsCollection();
        raf.writeInt(dirEntries.size());
        writtenSoFar += 4;

        offsets.put(dirName, new Long(writtenSoFar));

        // Write the offset of the file's data in the dir
        dirEntry.writtenOffsetOffset = 0L;
        raf.writeLong(0L);
        writtenSoFar += 8;
      }

      for (DirectoryEntry de : directoriesToWrite) {
        // Fix up the offset in the directory table
        long currFP = raf.getFilePointer();

        long offsetOffset = offsets.get(de.dirName).longValue();
        raf.seek(offsetOffset);
        raf.writeLong(writtenSoFar);

        raf.seek(currFP);

        // Now write each of the files in the DirectoryEntry
        List<Entry> list = de.getEntriesAsCollection();
        for (Entry zfie : list) {
          // Write the name bytes
          byte[] zfieNameBytes = zfie.name.getBytes("UTF-8");
          int zfieNameBytesLen = zfieNameBytes.length;
          raf.writeInt(zfieNameBytesLen);
          writtenSoFar += 4;
          raf.write(zfieNameBytes);
          writtenSoFar += zfieNameBytesLen;

          // Write isDir
          raf.writeByte(zfie.isDir ? (byte) 1 : (byte) 0);
          writtenSoFar += 1;

          // Write offset of bytes in the real Jar/Zip file
          raf.writeInt(zfie.offset);
          writtenSoFar += 4;

          // Write size of the file in the real Jar/Zip file
          raf.writeInt(zfie.size);
          writtenSoFar += 4;

          // Write compressed size of the file in the real Jar/Zip file
          raf.writeInt(zfie.compressedSize);
          writtenSoFar += 4;

          // Write java time stamp of the file in the real Jar/Zip file
          raf.writeLong(zfie.getLastModified());
          writtenSoFar += 8;
        }
      }
    } catch (Throwable t) {
      // Do nothing
    } finally {
      try {
        if (raf != null) {
          raf.close();
        }
      } catch (IOException ioe) {
        // Do nothing
      }
    }

    return ret;
  }
示例#17
0
 /**
  * ***** This writes the binary byte to the file. Later, use readBinaryByte to read the value from
  * the file.
  */
 public void writeBinaryByte(int col, int row, byte b) throws IOException {
   raf.seek(row * nBytesPerRow + columnStartAt[col]);
   raf.writeByte(b);
 }
 private void markDirty() throws IOException {
   lockFileAccess.seek(STATE_REGION_POS);
   lockFileAccess.writeByte(STATE_REGION_PROTOCOL);
   lockFileAccess.writeBoolean(false);
   assert lockFileAccess.getFilePointer() == STATE_REGION_SIZE + STATE_REGION_POS;
 }
 /* @see java.io.DataOutput.writeByte(int) */
 public void writeByte(int v) throws IOException {
   raf.writeByte(v);
 }
    private java.nio.channels.FileLock lock(FileLockManager.LockMode lockMode) throws Throwable {
      LOGGER.debug(
          "Waiting to acquire {} lock on {}.", lockMode.toString().toLowerCase(), displayName);
      long timeout = System.currentTimeMillis() + lockTimeoutMs;

      // Lock the state region, with the requested mode
      java.nio.channels.FileLock stateRegionLock = lockStateRegion(lockMode, timeout);
      if (stateRegionLock == null) {
        // Can't acquire lock, get details of owner to include in the error message
        String ownerPid = "unknown";
        String ownerOperation = "unknown";
        java.nio.channels.FileLock informationRegionLock =
            lockInformationRegion(LockMode.Shared, timeout);
        if (informationRegionLock == null) {
          LOGGER.debug("Could not lock information region for {}. Ignoring.", displayName);
        } else {
          try {
            if (lockFileAccess.length() <= INFORMATION_REGION_POS) {
              LOGGER.debug(
                  "Lock file for {} is too short to contain information region. Ignoring.",
                  displayName);
            } else {
              lockFileAccess.seek(INFORMATION_REGION_POS);
              if (lockFileAccess.readByte() != INFORMATION_REGION_PROTOCOL) {
                throw new IllegalStateException(
                    String.format(
                        "Unexpected lock protocol found in lock file '%s' for %s.",
                        lockFile, displayName));
              }
              ownerPid = lockFileAccess.readUTF();
              ownerOperation = lockFileAccess.readUTF();
            }
          } finally {
            informationRegionLock.release();
          }
        }

        throw new LockTimeoutException(
            String.format(
                "Timeout waiting to lock %s. It is currently in use by another Gradle instance.%nOwner PID: %s%nOur PID: %s%nOwner Operation: %s%nOur operation: %s%nLock file: %s",
                displayName,
                ownerPid,
                metaDataProvider.getProcessIdentifier(),
                ownerOperation,
                operationDisplayName,
                lockFile));
      }

      try {
        if (lockFileAccess.length() > 0) {
          lockFileAccess.seek(STATE_REGION_POS);
          if (lockFileAccess.readByte() != STATE_REGION_PROTOCOL) {
            throw new IllegalStateException(
                String.format(
                    "Unexpected lock protocol found in lock file '%s' for %s.",
                    lockFile, displayName));
          }
        }

        if (!stateRegionLock.isShared()) {
          // We have an exclusive lock (whether we asked for it or not).
          // Update the state region
          if (lockFileAccess.length() < STATE_REGION_SIZE) {
            // File did not exist before locking
            lockFileAccess.seek(STATE_REGION_POS);
            lockFileAccess.writeByte(STATE_REGION_PROTOCOL);
            lockFileAccess.writeBoolean(false);
          }
          // Acquire an exclusive lock on the information region and write our details there
          java.nio.channels.FileLock informationRegionLock =
              lockInformationRegion(LockMode.Exclusive, timeout);
          if (informationRegionLock == null) {
            throw new IllegalStateException(
                String.format(
                    "Timeout waiting to lock the information region for lock %s", displayName));
          }
          // check that the length of the reserved region is enough for storing our content
          try {
            lockFileAccess.seek(INFORMATION_REGION_POS);
            lockFileAccess.writeByte(INFORMATION_REGION_PROTOCOL);
            lockFileAccess.writeUTF(trimIfNecessary(metaDataProvider.getProcessIdentifier()));
            lockFileAccess.writeUTF(trimIfNecessary(operationDisplayName));
            lockFileAccess.setLength(lockFileAccess.getFilePointer());
          } finally {
            informationRegionLock.release();
          }
        }
      } catch (Throwable t) {
        stateRegionLock.release();
        throw t;
      }

      LOGGER.debug("Lock acquired.");
      return stateRegionLock;
    }
示例#21
0
  public static void main(String args[]) throws Exception {

    int index;

    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    DatagramSocket clientSocket = new DatagramSocket();

    byte[] sendData = new byte[1024];
    byte[] receiveData = new byte[1024];

    // Pull the target host from the command line.
    InetAddress ipAddress = null;
    if (args.length > 0) {
      ipAddress = InetAddress.getByName(args[0]);
    } else {
      System.err.println("FATAL: You must specify a hast to connect to.");
      System.exit(1);
    }

    // Get the request string from input and send it off.
    String request = inFromUser.readLine();
    sendData = request.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, PORT);
    clientSocket.send(sendPacket);

    // Get the header packet.
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    receiveData = receivePacket.getData();

    String[] words = new String[8];
    words = (new String(receiveData)).split("\\s+");

    int numBytes = Integer.parseInt(words[1]);

    boolean[] packets = new boolean[numBytes];

    File download_file = new File("downloaded_file");
    download_file.createNewFile();

    RandomAccessFile download = new RandomAccessFile(download_file, "rw");
    download.setLength(numBytes);

    clientSocket.setSoTimeout(1000);

    // Get the server's response.
    do {
      try {
        while (true) {
          receivePacket = new DatagramPacket(receiveData, receiveData.length);
          clientSocket.receive(receivePacket);
          receiveData = receivePacket.getData();

          // Convert the first two bytes back into the integer index of this packet.
          index = 256 * (receiveData[0] & 0xff) + (receiveData[1] & 0xff);
          packets[index] = true;
          download.seek(index * 1022);

          for (int i = 0; i < 1021; ++i) {
            download.writeByte(receiveData[i + 2]);
          }
        }
      } catch (Exception e) {
      }
    } while (moreToDo(packets));
  }
  /**
   * Write tag to file
   *
   * @param tag
   * @param raf
   * @param rafTemp
   * @throws CannotWriteException
   * @throws IOException
   */
  public void write(Tag tag, RandomAccessFile raf, RandomAccessFile rafTemp)
      throws CannotWriteException, IOException {
    logger.config("Writing tag");

    MetadataBlockInfo blockInfo = new MetadataBlockInfo();

    // Read existing data
    FlacStreamReader flacStream = new FlacStreamReader(raf);
    try {
      flacStream.findStream();
    } catch (CannotReadException cre) {
      throw new CannotWriteException(cre.getMessage());
    }

    boolean isLastBlock = false;
    while (!isLastBlock) {
      MetadataBlockHeader mbh = MetadataBlockHeader.readHeader(raf);
      switch (mbh.getBlockType()) {
        case STREAMINFO:
          {
            blockInfo.streamInfoBlock =
                new MetadataBlock(mbh, new MetadataBlockDataStreamInfo(mbh, raf));
            break;
          }

        case VORBIS_COMMENT:
        case PADDING:
        case PICTURE:
          {
            // All these will be replaced by the new metadata so we just treat as padding in order
            // to determine how much space is already allocated in the file
            raf.seek(raf.getFilePointer() + mbh.getDataLength());
            MetadataBlockData mbd = new MetadataBlockDataPadding(mbh.getDataLength());
            blockInfo.metadataBlockPadding.add(new MetadataBlock(mbh, mbd));
            break;
          }
        case APPLICATION:
          {
            MetadataBlockData mbd = new MetadataBlockDataApplication(mbh, raf);
            blockInfo.metadataBlockApplication.add(new MetadataBlock(mbh, mbd));
            break;
          }
        case SEEKTABLE:
          {
            MetadataBlockData mbd = new MetadataBlockDataSeekTable(mbh, raf);
            blockInfo.metadataBlockSeekTable.add(new MetadataBlock(mbh, mbd));
            break;
          }
        case CUESHEET:
          {
            MetadataBlockData mbd = new MetadataBlockDataCueSheet(mbh, raf);
            blockInfo.metadataBlockCueSheet.add(new MetadataBlock(mbh, mbd));
            break;
          }
        default:
          {
            // What are the consequences of doing this
            raf.seek(raf.getFilePointer() + mbh.getDataLength());
            break;
          }
      }
      isLastBlock = mbh.isLastBlock();
    }

    // Number of bytes in the existing file available before audio data
    int availableRoom = computeAvailableRoom(blockInfo);

    // Minimum Size of the New tag data without padding
    int newTagSize = tc.convert(tag).limit();

    // Number of bytes required for new tagdata and other metadata blocks
    int neededRoom = newTagSize + computeNeededRoom(blockInfo);

    // Go to start of Flac within file
    raf.seek(flacStream.getStartOfFlacInFile());

    logger.config("Writing tag available bytes:" + availableRoom + ":needed bytes:" + neededRoom);

    // There is enough room to fit the tag without moving the audio just need to
    // adjust padding accordingly need to allow space for padding header if padding required
    if ((availableRoom == neededRoom)
        || (availableRoom > neededRoom + MetadataBlockHeader.HEADER_LENGTH)) {
      // Jump over Id3 (if exists) Flac and StreamInfoBlock
      raf.seek(flacStream.getStartOfFlacInFile() + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH);

      // Write StreamInfo, we always write this first even if wasn't first in original spec
      raf.write(blockInfo.streamInfoBlock.getHeader().getBytesWithoutIsLastBlockFlag());
      raf.write(blockInfo.streamInfoBlock.getData().getBytes());

      // Write Application Blocks
      for (MetadataBlock aMetadataBlockApplication : blockInfo.metadataBlockApplication) {
        raf.write(aMetadataBlockApplication.getHeader().getBytesWithoutIsLastBlockFlag());
        raf.write(aMetadataBlockApplication.getData().getBytes());
      }

      // Write Seek Table Blocks
      for (MetadataBlock aMetadataBlockSeekTable : blockInfo.metadataBlockSeekTable) {
        raf.write(aMetadataBlockSeekTable.getHeader().getBytesWithoutIsLastBlockFlag());
        raf.write(aMetadataBlockSeekTable.getData().getBytes());
      }

      // Write Cue sheet Blocks
      for (MetadataBlock aMetadataBlockCueSheet : blockInfo.metadataBlockCueSheet) {
        raf.write(aMetadataBlockCueSheet.getHeader().getBytesWithoutIsLastBlockFlag());
        raf.write(aMetadataBlockCueSheet.getData().getBytes());
      }

      // Write tag (and padding)
      raf.getChannel().write(tc.convert(tag, availableRoom - neededRoom));
    }
    // Need to move audio
    else {
      // Skip to start of Audio

      // If Flac tag contains ID3header or something before start of official Flac header copy it
      // over
      if (flacStream.getStartOfFlacInFile() > 0) {
        raf.seek(0);
        rafTemp.getChannel().transferFrom(raf.getChannel(), 0, flacStream.getStartOfFlacInFile());
        rafTemp.seek(flacStream.getStartOfFlacInFile());
      }
      rafTemp.writeBytes(FlacStreamReader.FLAC_STREAM_IDENTIFIER);
      rafTemp.writeByte(0); // To ensure never set Last-metadata-block flag even if was before

      int uptoStreamHeaderSize =
          flacStream.getStartOfFlacInFile()
              + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH
              + MetadataBlockHeader.BLOCK_TYPE_LENGTH;
      rafTemp.seek(uptoStreamHeaderSize);
      raf.seek(uptoStreamHeaderSize);

      rafTemp
          .getChannel()
          .transferFrom(
              raf.getChannel(),
              uptoStreamHeaderSize,
              MetadataBlockHeader.BLOCK_LENGTH
                  + MetadataBlockDataStreamInfo.STREAM_INFO_DATA_LENGTH);

      int dataStartSize =
          flacStream.getStartOfFlacInFile()
              + FlacStreamReader.FLAC_STREAM_IDENTIFIER_LENGTH
              + MetadataBlockHeader.HEADER_LENGTH
              + MetadataBlockDataStreamInfo.STREAM_INFO_DATA_LENGTH;
      rafTemp.seek(dataStartSize);

      // Write all the metadatablocks
      for (MetadataBlock aMetadataBlockApplication : blockInfo.metadataBlockApplication) {
        rafTemp.write(aMetadataBlockApplication.getHeader().getBytesWithoutIsLastBlockFlag());
        rafTemp.write(aMetadataBlockApplication.getData().getBytes());
      }

      for (MetadataBlock aMetadataBlockSeekTable : blockInfo.metadataBlockSeekTable) {
        rafTemp.write(aMetadataBlockSeekTable.getHeader().getBytesWithoutIsLastBlockFlag());
        rafTemp.write(aMetadataBlockSeekTable.getData().getBytes());
      }

      for (MetadataBlock aMetadataBlockCueSheet : blockInfo.metadataBlockCueSheet) {
        rafTemp.write(aMetadataBlockCueSheet.getHeader().getBytesWithoutIsLastBlockFlag());
        rafTemp.write(aMetadataBlockCueSheet.getData().getBytes());
      }

      // Write tag data use default padding
      rafTemp.write(tc.convert(tag, FlacTagCreator.DEFAULT_PADDING).array());
      // Write audio to new file
      raf.seek(dataStartSize + availableRoom);

      // Issue #385
      // Transfer 'size' bytes from raf at its current position to rafTemp at position but do it in
      // batches
      // to prevent OutOfMemory exceptions
      long amountToBeWritten = raf.getChannel().size() - raf.getChannel().position();
      long written = 0;
      long chunksize = TagOptionSingleton.getInstance().getWriteChunkSize();
      long count = amountToBeWritten / chunksize;
      long mod = amountToBeWritten % chunksize;
      for (int i = 0; i < count; i++) {
        written +=
            rafTemp
                .getChannel()
                .transferFrom(raf.getChannel(), rafTemp.getChannel().position(), chunksize);
        rafTemp.getChannel().position(rafTemp.getChannel().position() + chunksize);
      }
      written +=
          rafTemp.getChannel().transferFrom(raf.getChannel(), rafTemp.getChannel().position(), mod);
      if (written != amountToBeWritten) {
        throw new CannotWriteException(
            "Was meant to write "
                + amountToBeWritten
                + " bytes but only written "
                + written
                + " bytes");
      }
    }
  }