Java File Read via ByteBuffer readBytes(InputStream is)

Here you can find the source of readBytes(InputStream is)

Description

read Bytes

License

Open Source License

Declaration

public static int readBytes(InputStream is) 

Method Source Code


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

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

public class Main {
    private static final Integer SANITY_CHECK_MAX_INT = 100000;

    public static int readBytes(InputStream is) {
        try {//from w  ww.  j  a  va 2  s  .c  om
            byte[] data = new byte[4];
            is.read(data);
            int result = byteArrayToInt(data);
            if (result > SANITY_CHECK_MAX_INT) {
                throw new RuntimeException("Too large number");
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static int byteArrayToInt(byte[] bytes) {
        if (bytes.length != 4) {
            throw new RuntimeException("Not integer");
        }
        return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
    }
}

Related

  1. readBinaryFileAsFloats(String fileName)
  2. readByte(String filePath)
  3. readBytes(File f)
  4. readBytes(final InputStream in, final int length)
  5. readBytes(final String file)
  6. readBytes(Path file)
  7. readBytes(ReadableByteChannel channel, byte[] array)
  8. readBytes(String file)
  9. readCode(byte[] message)