Example usage for java.io DataInputStream readUnsignedShort

List of usage examples for java.io DataInputStream readUnsignedShort

Introduction

In this page you can find the example usage for java.io DataInputStream readUnsignedShort.

Prototype

public final int readUnsignedShort() throws IOException 

Source Link

Document

See the general contract of the readUnsignedShort method of DataInput.

Usage

From source file:Main.java

public static void main(String[] args) throws IOException {
    short[] s = { -5, 32767 };
    FileOutputStream fos = new FileOutputStream("c:\\test.txt");
    DataOutputStream dos = new DataOutputStream(fos);
    for (short j : s) {
        dos.writeShort(j);/*w  w w  .  ja  v  a  2  s . c  o m*/
    }
    dos.flush();
    InputStream is = new FileInputStream("c:\\test.txt");
    DataInputStream dis = new DataInputStream(is);
    while (dis.available() > 0) {
        int k = dis.readUnsignedShort();
        System.out.print(k);
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    DataInputStream in = new DataInputStream(new FileInputStream("Main.class"));

    int start = in.readInt();
    if (start != 0xcafebabe) {
        System.out.println("not valid");
    }//from w  ww .j ava2 s  . c o m
    in.close();
    System.out.println(in.readUnsignedShort() + "/" + in.readUnsignedShort());

}

From source file:com.igormaznitsa.jhexed.swing.editor.filecontainer.FileContainer.java

private List<FileContainerSection> loadFromStream(final InputStream in) throws IOException {
    final DataInputStream din = in instanceof DataInputStream ? (DataInputStream) in : new DataInputStream(in);

    if (din.readInt() != MAGIC) {
        throw new IOException("Wrong format, can't find magic");
    }//from   w  ww.  j a  v a  2 s. c om

    final int version = din.readShort() & 0xFFFF;

    if (version > FORMAT_VERSION) {
        throw new IllegalArgumentException("Detected unsupported version [" + version + ']');
    }

    final int sectionNumber = din.readUnsignedShort();

    final List<FileContainerSection> result = new ArrayList<FileContainerSection>(Math.max(5, sectionNumber));

    for (int i = 0; i < sectionNumber; i++) {
        final FileContainerSection s = new FileContainerSection(in);
        result.add(s);
    }
    if (din.readInt() != MAGIC) {
        throw new IOException("Can't detecte the end MAGIC");
    }

    return result;
}

From source file:com.ocpsoft.pretty.faces.config.annotation.ByteCodeAnnotationFilter.java

/**
 * <p>/* w  w w. ja v a 2 s . co  m*/
 * Checks whether that supplied {@link InputStream} contains a Java class
 * file that might contain PrettyFaces annotations.
 * </p>
 * <p>
 * The caller of this method is responsible to close the supplied
 * {@link InputStream}. This method won't do it!
 * </p>
 * 
 * @param classFileStream
 *           The stream to read the class file from.
 * @return <code>true</code> for files that should be further checked for
 *         annotations
 * @throws IOException
 *            for any kind of IO problem
 */
@SuppressWarnings("unused")
public boolean accept(InputStream classFileStream) throws IOException {

    // open a DataInputStream
    DataInputStream in = new DataInputStream(classFileStream);

    // read magic and abort if it doesn't match
    int magic = in.readInt();
    if (magic != CLASS_FILE_MAGIC) {
        if (log.isDebugEnabled()) {
            log.debug("Magic not found! Not a valid class file!");
        }
        return false;
    }

    // check for at least JDK 1.5
    int minor = in.readUnsignedShort();
    int major = in.readUnsignedShort();
    if (major < 49) {
        // JDK 1.4 or less
        if (log.isTraceEnabled()) {
            log.trace("Not a JDK5 class! It cannot contain annotations!");
        }
        return false;
    }

    // this values is equal to the number entries in the constants pool + 1
    int constantPoolEntries = in.readUnsignedShort() - 1;

    // loop over all entries in the constants pool
    for (int i = 0; i < constantPoolEntries; i++) {

        // the tag to identify the record type
        int tag = in.readUnsignedByte();

        // process record according to its type
        switch (tag) {

        case CONSTANT_Class:
            /*
             * CONSTANT_Class_info { 
             *   u1 tag; 
             *   u2 name_index; 
             * }
             */
            in.readUnsignedShort();
            break;

        case CONSTANT_Fieldref:
        case CONSTANT_Methodref:
        case CONSTANT_InterfaceMethodref:
            /*
             * CONSTANT_[Fieldref|Methodref|InterfaceMethodref]_info { 
             *   u1 tag; 
             *   u2 class_index; 
             *   u2 name_and_type_index; 
             * }
             */
            in.readUnsignedShort();
            in.readUnsignedShort();
            break;

        case CONSTANT_String:
            /*
             * CONSTANT_String_info { 
             *   u1 tag; 
             *   u2 string_index; 
             * }
             */
            in.readUnsignedShort();
            break;

        case CONSTANT_Integer:
        case CONSTANT_Float:
            /*
             * CONSTANT_[Integer|Float]_info { 
             *   u1 tag; 
             *   u4 bytes; 
             * }
             */
            in.readInt();
            break;

        case CONSTANT_Long:
        case CONSTANT_Double:

            /*
             * CONSTANT_Long_info { 
             *   u1 tag; 
             *   u4 high_bytes; 
             *   u4 low_bytes; 
             * }
             */
            in.readLong();

            /*
             * We must increase the constant pool index because this tag
             * type takes two entries
             */
            i++;

            break;

        case CONSTANT_NameAndType:
            /*
             * CONSTANT_NameAndType_info { 
             *   u1 tag; 
             *   u2 name_index; 
             *   u2 descriptor_index; 
             * }
             */
            in.readUnsignedShort();
            in.readUnsignedShort();
            break;

        case CONSTANT_Utf8:
            /*
             * CONSTANT_Utf8_info { 
             *   u1 tag; 
             *   u2 length; 
             *   u1 bytes[length]; 
             * }
             */
            String str = in.readUTF();

            // check if this string sounds interesting
            if (str.contains(SEARCH_STRING)) {
                if (log.isTraceEnabled()) {
                    log.trace("Found PrettyFaces annotation reference in constant pool: " + str);
                }
                return true;
            }
            break;

        default:
            /*
             * Unknown tag! Should not happen! We will scan the class in this case.
             */
            if (log.isDebugEnabled()) {
                log.debug("Unknown constant pool tag found: " + tag);
            }
            return true;
        }
    }

    /*
     * We are finished with reading the interesting parts of the class file.
     * We stop here because the file doesn't seem to be interesting.
     */
    if (log.isTraceEnabled()) {
        log.trace("No reference to PrettyFaces annotations found!");
    }
    return false;

}

From source file:org.tacografo.file.FileBlockTGD.java

/**
 * Lectura de los bloques con formato :tag(fid)-longitud-value
 * //ww w . j a v a2  s . c  o m
 * @param entrada
 * @throws IOException
 * @throws ErrorFile ocurrido cuando no es un fichero tgd o falla en la lectura de algun bloque
 * porque no encuentre el tag(fid)
 */
private void lectura_bloque(DataInputStream entrada) throws IOException, ErrorFile {
    boolean existe_fid = true;
    while (existe_fid) {
        // la lectura tiene que ser con readUnsignedShort debido a que
        // los fid c108 y c100
        // los detecta con signo y me los rellenas como ffffc108 y
        // ffffc100
        int fid = entrada.readUnsignedShort();

        existe_fid = this.existe_Fid(fid);
        if (existe_fid) {
            // tipo de archivo 0 = bloque de dato -- 1 = certificado
            byte tipo = entrada.readByte();
            Integer longitud = Integer.valueOf(entrada.readChar());
            byte[] datos = new byte[longitud];

            entrada.read(datos, 0, longitud);
            // tipo de bloque
            if (tipo == 0) {
                CardBlock block = FactoriaBloques.getFactoria(fid, datos);
                if (block != null) {
                    this.lista_bloque.put(block.getFID(), block);
                }

            }
        } else {
            throw new ErrorFile();
        }
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.ClassVersionChecker.java

private void checkClassVersion(String filename) throws IOException {

    DataInputStream in = null;

    try {//w  w w.j a  v a 2 s.  c o  m
        //noinspection IOResourceOpenedButNotSafelyClosed
        in = new DataInputStream(new FileInputStream(filename));

        int magic = in.readInt();

        //        The first 4 bytes are a magic number, 0xCAFEBABe, to identify a valid class file
        //        then the next 2 bytes identify the class format version (major and minor).
        //        Possible major/minor value :
        //
        //        major  minor Java platform version
        //        45       3           1.0
        //        45       3           1.1
        //        46       0           1.2
        //        47       0           1.3
        //        48       0           1.4
        //        49       0           1.5
        //        50       0           1.6

        if (magic != 0xcafebabe)
            LOGGER.info(filename + " is not a valid class!");
        int minor = in.readUnsignedShort();
        int major = in.readUnsignedShort();
        LOGGER.info(filename + ": " + major + " . " + minor);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java

@Override
public int countTimeBytesSamples(final byte[] timeBytes) {
    int count = 0;
    try {//from w  w w.j  a v a  2 s .c o  m
        final ByteArrayInputStream byteStream = new ByteArrayInputStream(timeBytes);
        final DataInputStream byteDataStream = new DataInputStream(byteStream);
        int opcode;
        while ((opcode = byteDataStream.read()) != -1) {
            if (opcode == TimelineOpcode.FULL_TIME.getOpcodeIndex()) {
                byteDataStream.readInt();
                count++;
            } else if (opcode <= TimelineOpcode.MAX_DELTA_TIME) {
                count++;
            } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()) {
                count += byteDataStream.read();
                byteDataStream.read();
            } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()) {
                count += byteDataStream.readUnsignedShort();
                byteDataStream.read();
            } else {
                throw new IllegalStateException(String
                        .format("In TimelineCoder.countTimeBytesSamples(), unrecognized opcode %d", opcode));
            }
        }
        return count;
    } catch (IOException e) {
        log.error(e, "IOException while counting timeline samples");
        return count;
    }
}

From source file:net.minecraftforge.fml.repackage.com.nothome.delta.GDiffPatcher.java

/**
 * Patches to an output stream.//from   w w w  .j  a  v  a 2  s .  co m
 */
public void patch(SeekableSource source, InputStream patch, OutputStream out) throws IOException {

    DataOutputStream outOS = new DataOutputStream(out);
    DataInputStream patchIS = new DataInputStream(patch);

    // the magic string is 'd1 ff d1 ff' + the version number
    if (patchIS.readUnsignedByte() != 0xd1 || patchIS.readUnsignedByte() != 0xff
            || patchIS.readUnsignedByte() != 0xd1 || patchIS.readUnsignedByte() != 0xff
            || patchIS.readUnsignedByte() != 0x04) {

        throw new PatchException("magic string not found, aborting!");
    }

    while (true) {
        int command = patchIS.readUnsignedByte();
        if (command == EOF)
            break;
        int length;
        int offset;

        if (command <= DATA_MAX) {
            append(command, patchIS, outOS);
            continue;
        }

        switch (command) {
        case DATA_USHORT: // ushort, n bytes following; append
            length = patchIS.readUnsignedShort();
            append(length, patchIS, outOS);
            break;
        case DATA_INT: // int, n bytes following; append
            length = patchIS.readInt();
            append(length, patchIS, outOS);
            break;
        case COPY_USHORT_UBYTE:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readUnsignedByte();
            copy(offset, length, source, outOS);
            break;
        case COPY_USHORT_USHORT:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readUnsignedShort();
            copy(offset, length, source, outOS);
            break;
        case COPY_USHORT_INT:
            offset = patchIS.readUnsignedShort();
            length = patchIS.readInt();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_UBYTE:
            offset = patchIS.readInt();
            length = patchIS.readUnsignedByte();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_USHORT:
            offset = patchIS.readInt();
            length = patchIS.readUnsignedShort();
            copy(offset, length, source, outOS);
            break;
        case COPY_INT_INT:
            offset = patchIS.readInt();
            length = patchIS.readInt();
            copy(offset, length, source, outOS);
            break;
        case COPY_LONG_INT:
            long loffset = patchIS.readLong();
            length = patchIS.readInt();
            copy(loffset, length, source, outOS);
            break;
        default:
            throw new IllegalStateException("command " + command);
        }
    }
    outOS.flush();
}

From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java

@Override
public List<DateTime> decompressDateTimes(final byte[] compressedTimes) {
    final List<DateTime> dateTimeList = new ArrayList<DateTime>(compressedTimes.length * 4);
    final ByteArrayInputStream byteStream = new ByteArrayInputStream(compressedTimes);
    final DataInputStream byteDataStream = new DataInputStream(byteStream);
    int opcode = 0;
    int lastTime = 0;
    try {/* ww w  .  j a v  a2  s  .c  om*/
        while (true) {
            opcode = byteDataStream.read();
            if (opcode == -1) {
                break;
            }

            if (opcode == TimelineOpcode.FULL_TIME.getOpcodeIndex()) {
                lastTime = byteDataStream.readInt();
                dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
            } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()) {
                final int repeatCount = byteDataStream.readUnsignedByte();
                final int delta = byteDataStream.readUnsignedByte();
                for (int i = 0; i < repeatCount; i++) {
                    lastTime = lastTime + delta;
                    dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
                }
            } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()) {
                final int repeatCount = byteDataStream.readUnsignedShort();
                final int delta = byteDataStream.readUnsignedByte();
                for (int i = 0; i < repeatCount; i++) {
                    lastTime = lastTime + delta;
                    dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
                }
            } else {
                // The opcode is itself a singleton delta
                lastTime = lastTime + opcode;
                dateTimeList.add(DateTimeUtils.dateTimeFromUnixSeconds(lastTime));
            }
        }
    } catch (IOException e) {
        log.error(e, "In decompressTimes(), exception decompressing");
    }
    return dateTimeList;
}

From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java

private byte[] combineTimelines(final List<byte[]> timesList) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final DataOutputStream dataStream = new DataOutputStream(outputStream);
    try {//  w ww. j  a  va2 s .co  m
        int lastTime = 0;
        int lastDelta = 0;
        int repeatCount = 0;
        int chunkCounter = 0;
        for (byte[] times : timesList) {
            final ByteArrayInputStream byteStream = new ByteArrayInputStream(times);
            final DataInputStream byteDataStream = new DataInputStream(byteStream);
            int byteCursor = 0;
            while (true) {
                // Part 1: Get the opcode, and come up with newTime, newCount and newDelta
                final int opcode = byteDataStream.read();
                if (opcode == -1) {
                    break;
                }
                byteCursor++;
                int newTime = 0;
                int newCount = 0;
                int newDelta = 0;
                boolean useNewDelta = false;
                boolean nonDeltaTime = false;
                if (opcode == TimelineOpcode.FULL_TIME.getOpcodeIndex()) {
                    newTime = byteDataStream.readInt();
                    if (newTime < lastTime) {
                        log.warn(
                                "In TimelineCoder.combineTimeLines(), the fulltime read is %d, but the lastTime is %d; setting newTime to lastTime",
                                newTime, lastTime);
                        newTime = lastTime;
                    }
                    byteCursor += 4;
                    if (lastTime == 0) {
                        writeTime(0, newTime, dataStream);
                        lastTime = newTime;
                        lastDelta = 0;
                        repeatCount = 0;
                        continue;
                    } else if (newTime - lastTime <= TimelineOpcode.MAX_DELTA_TIME) {
                        newDelta = newTime - lastTime;
                        useNewDelta = true;
                        newCount = 1;
                    } else {
                        nonDeltaTime = true;
                    }
                } else if (opcode <= TimelineOpcode.MAX_DELTA_TIME) {
                    newTime = lastTime + opcode;
                    newDelta = opcode;
                    useNewDelta = true;
                    newCount = 1;
                } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()) {
                    newCount = byteDataStream.read();
                    newDelta = byteDataStream.read();
                    useNewDelta = true;
                    byteCursor += 2;
                    if (lastTime != 0) {
                        newTime = lastTime + newDelta * newCount;
                    } else {
                        throw new IllegalStateException(String.format(
                                "In TimelineCoder.combineTimelines, lastTime is 0 byte opcode = %d, byteCursor %d, chunkCounter %d, chunk %s",
                                opcode, byteCursor, chunkCounter, new String(Hex.encodeHex(times))));
                    }
                } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()) {
                    newCount = byteDataStream.readUnsignedShort();
                    newDelta = byteDataStream.read();
                    useNewDelta = true;
                    byteCursor += 3;
                    if (lastTime != 0) {
                        newTime = lastTime + newDelta * newCount;
                    }
                } else {
                    throw new IllegalStateException(String.format(
                            "In TimelineCoder.combineTimelines, Unrecognized byte opcode = %d, byteCursor %d, chunkCounter %d, chunk %s",
                            opcode, byteCursor, chunkCounter, new String(Hex.encodeHex(times))));
                }
                // Part 2: Combine existing state represented in lastTime, lastDelta and repeatCount with newTime, newCount and newDelta
                if (lastTime == 0) {
                    log.error("In combineTimelines(), lastTime is 0; byteCursor %d, chunkCounter %d, times %s",
                            byteCursor, chunkCounter, new String(Hex.encodeHex(times)));
                } else if (repeatCount > 0) {
                    if (lastDelta == newDelta && newCount > 0) {
                        repeatCount += newCount;
                        lastTime = newTime;
                    } else {
                        writeRepeatedDelta(lastDelta, repeatCount, dataStream);
                        if (useNewDelta) {
                            lastDelta = newDelta;
                            repeatCount = newCount;
                            lastTime = newTime;
                        } else {
                            writeTime(lastTime, newTime, dataStream);
                            lastTime = newTime;
                            lastDelta = 0;
                            repeatCount = 0;
                        }
                    }
                } else if (nonDeltaTime) {
                    writeTime(lastTime, newTime, dataStream);
                    lastTime = newTime;
                    lastDelta = 0;
                    repeatCount = 0;
                } else if (lastDelta == 0) {
                    lastTime = newTime;
                    repeatCount = newCount;
                    lastDelta = newDelta;
                }
            }
            chunkCounter++;
        }
        if (repeatCount > 0) {
            writeRepeatedDelta(lastDelta, repeatCount, dataStream);
        }
        dataStream.flush();
        return outputStream.toByteArray();
    } catch (Exception e) {
        log.error(e, "In combineTimesLines(), exception combining timelines");
        return new byte[0];
    }
}