Example usage for java.io DataInputStream read

List of usage examples for java.io DataInputStream read

Introduction

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

Prototype

public final int read(byte b[], int off, int len) throws IOException 

Source Link

Document

Reads up to len bytes of data from the contained input stream into an array of bytes.

Usage

From source file:com.adaptris.security.StdOutput.java

private static byte[] read(DataInputStream in) throws IOException {
    byte[] bytes = new byte[in.readInt()];
    if (bytes.length > 0) {
        in.read(bytes, 0, bytes.length);
    } else {//ww  w  .j av a 2 s .c o  m
        bytes = null;
    }
    return bytes;
}

From source file:FileUtil.java

public static byte[] readFileAsBytes(String path, Integer start, Integer length) {

    byte[] byteData = null;

    try {//w  w  w. ja  va  2  s  . co  m

        File file = new File(path);

        DataInputStream dis;
        dis = new DataInputStream(new FileInputStream(file));

        if (dis.available() > Integer.MAX_VALUE) {
            System.out.println("dis.available() > Integer.MAX_VALUE");
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream(length);
        byte[] bytes = new byte[length];

        dis.skipBytes(start);
        int readBytes = dis.read(bytes, 0, length);
        os.write(bytes, 0, readBytes);

        byteData = os.toByteArray();

        dis.close();
        os.close();

    } catch (Exception e) {
        System.out.println(e);
    }

    return byteData;
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Read a PKCS 8 format private key. */
private static PrivateKey readPrivateKey(InputStream file) throws IOException, GeneralSecurityException {
    final DataInputStream input = new DataInputStream(file);
    try {//www  .  ja  v  a  2s .c  o m
        byte[] bytes = new byte[10000];
        int nBytesTotal = 0, nBytes;
        while ((nBytes = input.read(bytes, nBytesTotal, 10000 - nBytesTotal)) != -1) {
            nBytesTotal += nBytes;
        }

        final byte[] bytes2 = new byte[nBytesTotal];
        System.arraycopy(bytes, 0, bytes2, 0, nBytesTotal);
        bytes = bytes2;

        KeySpec spec = decryptPrivateKey(bytes);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        try {
            return KeyFactory.getInstance("RSA").generatePrivate(spec);
        } catch (final InvalidKeySpecException ex) {
            return KeyFactory.getInstance("DSA").generatePrivate(spec);
        }
    } finally {
        input.close();
    }
}

From source file:org.elasticsearch.discovery.custom.DataFetcher.java

public static String fetchData(String url, ESLogger logger) {
    DataInputStream responseStream = null;
    try {//from w  ww. j ava  2s  . c om
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(1000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() != 200)
            throw new RuntimeException("Unable to get data for URL " + url);

        byte[] b = new byte[2048];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        responseStream = new DataInputStream((FilterInputStream) conn.getContent());
        int c = 0;
        while ((c = responseStream.read(b, 0, b.length)) != -1)
            bos.write(b, 0, c);
        String return_ = new String(bos.toByteArray(), CharEncoding.UTF_8);
        logger.info(String.format("Calling URL API: %s returns: %s", url, return_));
        conn.disconnect();
        return return_;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (responseStream != null)
                responseStream.close();
        } catch (Exception e) {
            logger.warn("Failed to close response stream from priam", e);
        }
    }
}

From source file:com.simiacryptus.util.Util.java

/**
 * Read byte [ ].//  w ww .ja v a 2 s  .  c  o m
 *
 * @param i the
 * @param s the s
 * @return the byte [ ]
 * @throws IOException the io exception
 */
@javax.annotation.Nonnull
public static byte[] read(@javax.annotation.Nonnull final DataInputStream i, final int s) throws IOException {
    @javax.annotation.Nonnull
    final byte[] b = new byte[s];
    int pos = 0;
    while (b.length > pos) {
        final int read = i.read(b, pos, b.length - pos);
        if (0 == read) {
            throw new RuntimeException();
        }
        pos += read;
    }
    return b;
}

From source file:io.hops.hopsworks.common.jobs.yarn.LogReader.java

/**
 * Keep calling this till you get a {@link EOFException} for getting logs of
 * all types for a single container.//from   www.  ja  v  a2  s. c  o  m
 *
 * @param valueStream
 * @param out
 * @throws IOException
 */
public static void readAContainerLogsForALogType(DataInputStream valueStream, PrintStream out)
        throws IOException {

    byte[] buf = new byte[65535];

    String fileType = valueStream.readUTF();
    String fileLengthStr = valueStream.readUTF();
    long fileLength = Long.parseLong(fileLengthStr);
    out.print("LogType: ");
    out.println(fileType);
    out.print("LogLength: ");
    out.println(fileLengthStr);
    out.println("Log Contents:");

    long curRead = 0;
    long pendingRead = fileLength - curRead;
    int toRead = pendingRead > buf.length ? buf.length : (int) pendingRead;
    int len = valueStream.read(buf, 0, toRead);
    while (len != -1 && curRead < fileLength) {
        out.write(buf, 0, len);
        curRead += len;

        pendingRead = fileLength - curRead;
        toRead = pendingRead > buf.length ? buf.length : (int) pendingRead;
        len = valueStream.read(buf, 0, toRead);
    }
    out.println("");
}

From source file:com.zotoh.core.io.StreamUte.java

/**
 * @param src/*from   w  w  w  . j  av  a 2 s.  com*/
 * @param out
 * @param bytesToCopy
 * @throws IOException
 */
@SuppressWarnings("unused")
public static void streamToStream(InputStream src, OutputStream out, long bytesToCopy) throws IOException {

    tstNonNegLongArg("bytes-to-read", bytesToCopy);
    tstObjArg("out-stream", out);
    tstObjArg("in-stream", src);

    DataInputStream dis = new DataInputStream(src);
    byte[] buff = new byte[4096];
    long cl = bytesToCopy;
    int bc = 0, c, tries = 0;

    while (cl > 0L) {
        c = dis.read(buff, 0, (int) Math.min(4096L, cl));
        if (c > 0) {
            bc += c;
            cl -= c;
            out.write(buff, 0, c);
        } else {
            // if we can't read all the bytes, then we dont want to loop forever, try 3 times, then come out
            if (tries == 3) {
                break;
            }
            safeThreadWait(500L);
            ++tries;
        }
    }

    safeFlush(out);
}

From source file:org.structr.core.graph.SyncCommand.java

public static byte[] deserializeData(final DataInputStream inputStream) throws IOException {

    final int len = inputStream.readInt();
    final byte[] buffer = new byte[len];

    inputStream.read(buffer, 0, len);

    return buffer;
}

From source file:com.bigdata.dastor.db.ReadResponse.java

public ReadResponse deserialize(DataInputStream dis) throws IOException {
    int digestSize = dis.readInt();
    byte[] digest = new byte[digestSize];
    dis.read(digest, 0, digestSize);
    boolean isDigest = dis.readBoolean();

    Row row = null;// w  ww.  ja v a2  s. c  o m
    if (!isDigest) {
        row = Row.serializer().deserialize(dis);
    }

    ReadResponse rmsg = isDigest ? new ReadResponse(digest) : new ReadResponse(row);
    rmsg.setIsDigestQuery(isDigest);
    return rmsg;
}

From source file:org.mule.transformer.simple.ByteArrayToModbusResponse.java

public Object doTransform(Object src, String outputEncoding) throws TransformerException {
    try {/*from  w  w w . j  av a 2 s . c  o m*/
        BytesInputStream m_ByteIn = new BytesInputStream((byte[]) src);
        DataInputStream m_Input = new DataInputStream(m_ByteIn);
        byte[] buffer = m_ByteIn.getBuffer();

        //read to byte length of message
        if (m_Input.read(buffer, 0, 6) == -1) {
            throw new ModbusIOException("Premature end of stream (Header truncated).");
        }
        //extract length of bytes following in message
        int bf = ModbusUtil.registerToShort(buffer, 4);
        //read rest
        if (m_Input.read(buffer, 6, bf) == -1) {
            throw new ModbusIOException("Premature end of stream (Message truncated).");
        }
        m_ByteIn.reset(buffer, (6 + bf));
        m_ByteIn.skip(7);
        int functionCode = m_ByteIn.readUnsignedByte();
        m_ByteIn.reset();
        ModbusResponse res = ModbusResponse.createModbusResponse(functionCode);
        res.readFrom(m_ByteIn);

        return res;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    }

}