Java File Write via ByteBuffer writeComment(File zipFile, String comment)

Here you can find the source of writeComment(File zipFile, String comment)

Description

write Comment

License

Open Source License

Declaration

public static void writeComment(File zipFile, String comment) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    private static final byte[] COMMENT_SIGN = new byte[] { 99, 104, 97, 110, 110, 101, 108 };

    public static void writeComment(File zipFile, String comment) throws IOException {
        // {@see java.util.zip.ZipOutputStream.writeEND}
        byte[] data = comment.getBytes("utf-8");
        final RandomAccessFile raf = new RandomAccessFile(zipFile, "rw");
        raf.seek(zipFile.length() - 2);//from ww w. j a  va2  s  .c om
        // write zip comment length
        // (content field length + length field length + sign field length)
        writeShort(data.length + 2 + COMMENT_SIGN.length, raf);
        // write content
        writeBytes(data, raf);
        // write content length
        writeShort(data.length, raf);
        // write sign bytes
        writeBytes(COMMENT_SIGN, raf);
        raf.close();
    }

    private static void writeShort(int i, DataOutput out) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
        bb.putShort((short) i);
        out.write(bb.array());
    }

    private static void writeBytes(byte[] data, DataOutput out) throws IOException {
        out.write(data);
    }
}

Related

  1. write(Path file, String content)
  2. write(SeekableByteChannel channel, long start, byte[] bytes)
  3. write24BitInteger(int integer, ByteOrder order)
  4. writeByte(WritableByteChannel channel, byte value)
  5. writeBytes(Path file, byte[] bytes)
  6. writeDataLengthsToHeader(FileOutputStream fpo)
  7. writeDelimitedToOutputStream(byte[] bytes, OutputStream outputStream)
  8. writeDouble(BufferedWriter bw, double[] buf)
  9. writeEmpty()