Java File Read via ByteBuffer readZipComment(File file)

Here you can find the source of readZipComment(File file)

Description

read Zip Comment

License

Open Source License

Declaration

public static String readZipComment(File file) 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;
import java.util.Arrays;

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

    public static String readZipComment(File file) throws IOException {
        RandomAccessFile raf = null;
        try {//from w ww.j  a  va  2  s .c  o m
            raf = new RandomAccessFile(file, "r");
            long index = raf.length();
            byte[] buffer = new byte[COMMENT_SIGN.length];
            index -= COMMENT_SIGN.length;
            // read sign bytes
            raf.seek(index);
            raf.readFully(buffer);
            // if sign bytes matched
            if (Arrays.equals(buffer, COMMENT_SIGN)) {
                index -= 2;
                raf.seek(index);
                // read content length field
                int length = readShort(raf);
                if (length > 0) {
                    index -= length;
                    raf.seek(index);
                    // read content bytes
                    byte[] bytesComment = new byte[length];
                    raf.readFully(bytesComment);
                    return new String(bytesComment, "utf-8");
                } else {
                    throw new IOException("Zip comment content not found");
                }
            } else {
                throw new IOException("Zip comment sign bytes not found");
            }
        } finally {
            if (raf != null) {
                raf.close();
            }
        }
    }

    private static short readShort(DataInput input) throws IOException {
        byte[] buf = new byte[2];
        input.readFully(buf);
        ByteBuffer bb = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
        return bb.getShort(0);
    }
}

Related

  1. readUtf8(DataInput in)
  2. readVarLong(byte[] arr)
  3. readWaveFile44100_16Bit_Mono(String dir, String name)
  4. readWavHeader(DataInputStream inStrm, FileChannel fc)
  5. readWholeFile(File file, StringBuilder stringBuilder)
  6. skip(final ReadableByteChannel input, final long toSkip)
  7. streamRead(SocketChannel in)