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 int read() throws IOException 

Source Link

Document

Reads the next byte of data from this input stream.

Usage

From source file:org.dcm4che2.tool.jpg2dcm.Jpg2Dcm.java

private void readHeader(DicomObject attrs, DataInputStream jpgInput) throws IOException {
    if (jpgInput.read() != FF || jpgInput.read() != SOI || jpgInput.read() != FF) {
        throw new IOException("JPEG stream does not start with FF D8 FF");
    }/*from   w w  w  .j a  va 2s. co  m*/
    int marker = jpgInput.read();
    int segmLen;
    boolean seenSOF = false;
    buffer[0] = (byte) FF;
    buffer[1] = (byte) SOI;
    buffer[2] = (byte) FF;
    buffer[3] = (byte) marker;
    jpgHeaderLen = 4;
    while (marker != SOS) {
        segmLen = jpgInput.readUnsignedShort();
        if (buffer.length < jpgHeaderLen + segmLen + 2) {
            growBuffer(jpgHeaderLen + segmLen + 2);
        }
        buffer[jpgHeaderLen++] = (byte) (segmLen >>> 8);
        buffer[jpgHeaderLen++] = (byte) segmLen;
        jpgInput.readFully(buffer, jpgHeaderLen, segmLen - 2);
        if ((marker & 0xf0) == SOF && marker != DHT && marker != DAC) {
            seenSOF = true;
            int p = buffer[jpgHeaderLen] & 0xff;
            int y = ((buffer[jpgHeaderLen + 1] & 0xff) << 8) | (buffer[jpgHeaderLen + 2] & 0xff);
            int x = ((buffer[jpgHeaderLen + 3] & 0xff) << 8) | (buffer[jpgHeaderLen + 4] & 0xff);
            int nf = buffer[jpgHeaderLen + 5] & 0xff;
            attrs.putInt(Tag.SamplesPerPixel, VR.US, nf);
            if (nf == 3) {
                attrs.putString(Tag.PhotometricInterpretation, VR.CS, "YBR_FULL_422");
                attrs.putInt(Tag.PlanarConfiguration, VR.US, 0);
            } else {
                attrs.putString(Tag.PhotometricInterpretation, VR.CS, "MONOCHROME2");
            }
            attrs.putInt(Tag.Rows, VR.US, y);
            attrs.putInt(Tag.Columns, VR.US, x);
            attrs.putInt(Tag.BitsAllocated, VR.US, p > 8 ? 16 : 8);
            attrs.putInt(Tag.BitsStored, VR.US, p);
            attrs.putInt(Tag.HighBit, VR.US, p - 1);
            attrs.putInt(Tag.PixelRepresentation, VR.US, 0);
        }
        if (noAPPn & (marker & 0xf0) == APP) {
            jpgLen -= segmLen + 2;
            jpgHeaderLen -= 4;
        } else {
            jpgHeaderLen += segmLen - 2;
        }
        if (jpgInput.read() != FF) {
            throw new IOException("Missing SOS segment in JPEG stream");
        }
        marker = jpgInput.read();
        buffer[jpgHeaderLen++] = (byte) FF;
        buffer[jpgHeaderLen++] = (byte) marker;
    }
    if (!seenSOF) {
        throw new IOException("Missing SOF segment in JPEG stream");
    }
}

From source file:org.opencastproject.util.IoSupport.java

/**
 * Convenience method to read in a file from either a remote or local source.
 *
 * @param url// w ww  .  ja v  a 2  s  .  c o  m
 *         The {@code URL} to read the source data from.
 * @param trustedClient
 *         The {@code TrustedHttpClient} which should be used to communicate with the remote server. This can be null
 *         for local file reads.
 * @return A String containing the source data or null in the case of an error.
 * @deprecated this method doesn't support UTF8 or handle HTTP response codes
 */
public static String readFileFromURL(URL url, TrustedHttpClient trustedClient) {
    StringBuilder sb = new StringBuilder();
    DataInputStream in = null;
    HttpResponse response = null;
    try {
        // Do different things depending on what we're reading...
        if ("file".equals(url.getProtocol())) {
            in = new DataInputStream(url.openStream());
        } else {
            if (trustedClient == null) {
                logger.error("Unable to read from remote source {} because trusted client is null!",
                        url.getFile());
                return null;
            }
            HttpGet get = new HttpGet(url.toURI());
            try {
                response = trustedClient.execute(get);
            } catch (TrustedHttpClientException e) {
                logger.warn("Unable to fetch file from {}.", url, e);
                trustedClient.close(response);
                return null;
            }
            in = new DataInputStream(response.getEntity().getContent());
        }
        int c = 0;
        while ((c = in.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        logger.warn("IOException attempting to get file from {}.", url);
        return null;
    } catch (URISyntaxException e) {
        logger.warn("URI error attempting to get file from {}.", url);
        return null;
    } catch (NullPointerException e) {
        logger.warn("Nullpointer attempting to get file from {}.", url);
        return null;
    } finally {
        IOUtils.closeQuietly(in);

        if (response != null && trustedClient != null) {
            trustedClient.close(response);
            response = null;
        }
    }

    return sb.toString();
}

From source file:halive.shootinoutside.common.core.game.map.GameMap.java

private void loadTilesFromByteArray(byte[] b) {
    initTileArray();/*from   w  w  w . j a va2 s .  c o  m*/
    ByteArrayInputStream input = new ByteArrayInputStream(b);
    DataInputStream in = new DataInputStream(input);
    for (int x = 0; x < tiles.length; x++) {
        for (int y = 0; y < tiles[x].length; y++) {
            try {
                tiles[x][y] = GameMapTileType.getTypeFomeTileID(in.read());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

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  av a2 s.  co  m*/
        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:net.contrapunctus.rngzip.io.RNGZSettings.java

/**
 * Reconstitute the settings from a given stream.
 *//*from ww  w .ja  v a2  s  .co  m*/
protected RNGZSettings fromStream(MultiplexInputStream mux, int stream) throws IOException {
    if (mux.magic() != magic()) {
        throw new RNGZFormatException("bad magic");
    }
    DataInputStream config = new DataInputStream(mux.open(stream));
    try {
        coding = BitCoding_values[config.read()];
        if (config.read() != 2) {
            throw new RNGZFormatException("invalid config data");
        }
        treeCompr = DataCompression_values[config.read()];
        dataCompr = DataCompression_values[config.read()];
    } catch (IndexOutOfBoundsException x) {
        throw new RNGZFormatException("unknown coding");
    }
    return this;
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void doReadWriteTestForInputStream(int count, String encCipherClass, String decCipherClass, byte[] iv)
        throws IOException {
    Cipher encCipher = getCipher(encCipherClass);
    LOG.debug("Created a cipher object of type: " + encCipherClass);

    // Generate data
    SecureRandom random = new SecureRandom();
    byte[] originalData = new byte[count];
    byte[] decryptedData = new byte[count];
    random.nextBytes(originalData);/*from w ww.  ja  v  a2 s .  c  o m*/
    LOG.debug("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CryptoOutputStream out = getCryptoOutputStream(encryptedData, encCipher, defaultBufferSize, iv, false);
    out.write(originalData, 0, originalData.length);
    out.flush();
    out.close();
    LOG.debug("Finished encrypting data");

    Cipher decCipher = getCipher(decCipherClass);
    LOG.debug("Created a cipher object of type: " + decCipherClass);

    // Decrypt data
    CryptoInputStream in = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()),
            decCipher, defaultBufferSize, iv, false);

    // Check
    int remainingToRead = count;
    int offset = 0;
    while (remainingToRead > 0) {
        int n = in.read(decryptedData, offset, decryptedData.length - offset);
        if (n >= 0) {
            remainingToRead -= n;
            offset += n;
        }
    }

    Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData);

    // Decrypt data byte-at-a-time
    in = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
            defaultBufferSize, iv, false);

    // Check
    DataInputStream originalIn = new DataInputStream(
            new BufferedInputStream(new ByteArrayInputStream(originalData)));
    int expected;
    do {
        expected = originalIn.read();
        Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read());
    } while (expected != -1);

    LOG.debug("SUCCESS! Completed checking " + count + " records");
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void doReadWriteTestForReadableByteChannel(int count, String encCipherClass, String decCipherClass,
        byte[] iv) throws IOException {
    Cipher encCipher = getCipher(encCipherClass);
    LOG.debug("Created a cipher object of type: " + encCipherClass);

    // Generate data
    SecureRandom random = new SecureRandom();
    byte[] originalData = new byte[count];
    byte[] decryptedData = new byte[count];
    random.nextBytes(originalData);//from   w  ww . j  a  v a  2 s. com
    LOG.debug("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CryptoOutputStream out = getCryptoOutputStream(encryptedData, encCipher, defaultBufferSize, iv, true);
    out.write(originalData, 0, originalData.length);
    out.flush();
    out.close();
    LOG.debug("Finished encrypting data");

    Cipher decCipher = getCipher(decCipherClass);
    LOG.debug("Created a cipher object of type: " + decCipherClass);

    // Decrypt data
    CryptoInputStream in = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()),
            decCipher, defaultBufferSize, iv, true);

    // Check
    int remainingToRead = count;
    int offset = 0;
    while (remainingToRead > 0) {
        int n = in.read(decryptedData, offset, decryptedData.length - offset);
        if (n >= 0) {
            remainingToRead -= n;
            offset += n;
        }
    }

    Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData);

    // Decrypt data byte-at-a-time
    in = getCryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()), decCipher,
            defaultBufferSize, iv, true);

    // Check
    DataInputStream originalIn = new DataInputStream(
            new BufferedInputStream(new ByteArrayInputStream(originalData)));
    int expected;
    do {
        expected = originalIn.read();
        Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read());
    } while (expected != -1);

    LOG.debug("SUCCESS! Completed checking " + count + " records");
}

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 {/*from   ww  w .  j  av a  2  s. c  o 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];
    }
}

From source file:com.bruce.study.demo.studydata.demos60.httpclient.MyHttpClientActivity.java

/**
 * ???//from  ww  w . j  av a  2 s .  c om
 */
private void getNetInfo() {
    DataInputStream dataInputStream = null;
    try {
        URL url = new URL(ADDRESS); // ??
        URLConnection urlConnection = url.openConnection(); // http
        // ??
        dataInputStream = new DataInputStream(urlConnection.getInputStream());
        // ??
        //                    DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream())
        // ???
        int temp = 0;
        byteArrayBuffer = new ByteArrayBuffer(1000);
        while ((temp = dataInputStream.read()) != -1) {
            byteArrayBuffer.append(temp);
        }
        // ??
        MyHttpClientActivity.this.sendUIMessageEmpty(0x02);
    } catch (MalformedURLException e) {
        logE(e.toString());
    } catch (IOException e) {
        logE(e.toString());
    } finally {
        try {
            if (dataInputStream != null) {
                dataInputStream.close();
            }
        } catch (IOException e) {
            logE(e.toString());
        }
    }
}

From source file:org.apache.fop.render.pdf.ImageRawPNGAdapter.java

/** {@inheritDoc} */
public void outputContents(OutputStream out) throws IOException {
    InputStream in = ((ImageRawStream) image).createInputStream();

    try {//from  ww  w.ja v  a2  s.c  o m
        if (numberOfInterleavedComponents == 1 || numberOfInterleavedComponents == 3) {
            // means we have Gray, RGB, or Palette
            IOUtils.copy(in, out);
        } else {
            // means we have Gray + alpha or RGB + alpha
            // TODO: since we have alpha here do this when the alpha channel is extracted
            int numBytes = numberOfInterleavedComponents - 1; // 1 for Gray, 3 for RGB
            int numColumns = image.getSize().getWidthPx();
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            int offset = 0;
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha
            // channel and then deflate the RGB channels back again
            DeflaterOutputStream dos = new DeflaterOutputStream(out, new Deflater());
            while ((filter = dataStream.read()) != -1) {
                byte[] bytes = new byte[bytesPerRow];
                dataStream.readFully(bytes, 0, bytesPerRow);
                dos.write((byte) filter);
                for (int j = 0; j < numColumns; j++) {
                    dos.write(bytes, offset, numBytes);
                    offset += numberOfInterleavedComponents;
                }
                offset = 0;
            }
            dos.close();
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}