Java Code Examples for java.io.InputStream.skip()

The following are Jave code examples for showing how to use skip() of the java.io.InputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: StreamUtil.java   View Source Code Vote up 7 votes
/**
 * Skips exactly bytesCount bytes in inputStream unless end of stream is reached first.
 *
 * @param inputStream input stream to skip bytes from
 * @param bytesCount number of bytes to skip
 * @return number of skipped bytes
 * @throws IOException
 */
public static long skip(final InputStream inputStream, final long bytesCount) throws IOException {
  Preconditions.checkNotNull(inputStream);
  Preconditions.checkArgument(bytesCount >= 0);

  long toSkip = bytesCount;
  while (toSkip > 0) {
    final long skipped = inputStream.skip(toSkip);
    if (skipped > 0) {
      toSkip -= skipped;
      continue;
    }

    if (inputStream.read() != -1) {
      toSkip--;
      continue;
    }
    return bytesCount - toSkip;
  }

  return bytesCount;
}
 
Example 2
Project: GitHub   File: TiffUtil.java   View Source Code Vote up 6 votes
/**
 * Positions the given input stream to the entry that has a specified tag. Tag will be consumed.
 * @param is the input stream of TIFF data positioned to the beginning of an IFD.
 * @param length length of the available data in the given input stream.
 * @param isLittleEndian whether the TIFF data is stored in little or big endian format
 * @param tagToFind tag to find
 * @return remaining length of the data on success, 0 on failure
 */
private static int moveToTiffEntryWithTag(
    InputStream is,
    int length,
    boolean isLittleEndian,
    int tagToFind)
    throws IOException {
  if (length < 14) {
    return 0;
  }
  // read the number of entries and go through all of them
  // each IFD entry has length of 12 bytes and is composed of
  // {TAG [2], TYPE [2], COUNT [4], VALUE/OFFSET [4]}
  int numEntries = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
  length -= 2;
  while (numEntries-- > 0 && length >= 12) {
    int tag = StreamProcessor.readPackedInt(is, 2, isLittleEndian);
    length -= 2;
    if (tag == tagToFind) {
      return length;
    }
    is.skip(10);
    length -= 10;
  }
  return 0;
}
 
Example 3
Project: util4j   File: InputStreamUtils.java   View Source Code Vote up 5 votes
public static void skipFully(InputStream is, long num_bytes) throws EOFException, IOException {
	long num_skipped = 0;
	while (num_skipped < num_bytes) {
		long just_skipped = is.skip(num_bytes - num_skipped);
		if (just_skipped > 0)
			num_skipped += just_skipped;
		else {
			if (is.read() < 0)
				throw new EOFException("Skipped only " + num_skipped + " bytes to end of file.");
			else
				++num_skipped;
		}
	}
}
 
Example 4
Project: NGB-master   File: MultipartFileSender.java   View Source Code Vote up 5 votes
private static void copy(InputStream input, OutputStream output, long inputSize, long start, long length)
        throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int read;

    if (inputSize == length) {
        // Write full range.
        while ((read = input.read(buffer)) > 0) {
            output.write(buffer, 0, read);
            output.flush();
        }
    } else {
        long skipped = input.skip(start);
        Assert.isTrue(skipped == start);

        long toRead = length;

        while ((read = input.read(buffer)) > 0) {
            toRead -= read;
            if (toRead > 0) {
                output.write(buffer, 0, read);
                output.flush();
            } else {
                output.write(buffer, 0, (int) toRead + read);
                output.flush();
                break;
            }
        }
    }
}
 
Example 5
Project: battsett   File: BattSett.java   View Source Code Vote up 5 votes
public int modbusWriteSingle(int uid, int address, int val) throws IOException {
  OutputStream os = socket.getOutputStream();

  byte[] req = new byte[] { 0, 1, 0, 0, 0, 6, (byte) uid, (byte) FNC_WRITE_SINGLE, // header
      (byte) (address / 256), (byte) (address % 256), 
      (byte) (val / 256), (byte) (val % 256)};

  os.write(req);
  os.flush();

  InputStream is = socket.getInputStream();
  is.skip(7); // ids
  int code = is.read();
  if (code == (FNC_ERR_FLAG | FNC_WRITE_SINGLE)) {
    int ec = is.read();
    if (ec == ERR_SLAVE_DEVICE_FAILURE)
      throw new RuntimeException("Modbus error. Check if 'Inverter control via Modbus' is enabled.");
    throw new RuntimeException("modbus error " + ec);
  }
  if (code != 6)
    throw new RuntimeException("modbus response error fnc = " + code);
  int response;
  byte[] buff = new byte[2];
  if (is.read(buff) == -1)  // address
    throw new RuntimeException("response error");
  if (is.read(buff) == -1)  // value
    throw new RuntimeException("response error");
  int hi = buff[0] & 0xFF;
  int lo = buff[1] & 0xFF;
  response = hi * 256 + lo;
  return response;
}
 
Example 6
Project: boohee_v5.6   File: TinkerZipFile.java   View Source Code Vote up 5 votes
public InputStream getInputStream(TinkerZipEntry entry) throws IOException {
    entry = getEntry(entry.getName());
    if (entry == null) {
        return null;
    }
    InputStream rafStream;
    RandomAccessFile localRaf = this.raf;
    synchronized (localRaf) {
        rafStream = new RAFStream(localRaf, entry.localHeaderRelOffset);
        DataInputStream is = new DataInputStream(rafStream);
        int localMagic = Integer.reverseBytes(is.readInt());
        if (((long) localMagic) != ZipConstants.LOCSIG) {
            throwZipException(this.filename, localRaf.length(), entry.getName(), entry
                    .localHeaderRelOffset, "Local File Header", localMagic);
        }
        is.skipBytes(2);
        int gpbf = Short.reverseBytes(is.readShort()) & 65535;
        if ((gpbf & 1) != 0) {
            throw new ZipException("Invalid General Purpose Bit Flag: " + gpbf);
        }
        is.skipBytes(18);
        int fileNameLength = Short.reverseBytes(is.readShort()) & 65535;
        int extraFieldLength = Short.reverseBytes(is.readShort()) & 65535;
        is.close();
        rafStream.skip((long) (fileNameLength + extraFieldLength));
        if (entry.compressionMethod == 0) {
            rafStream.endOffset = rafStream.offset + entry.size;
        } else {
            rafStream.endOffset = rafStream.offset + entry.compressedSize;
        }
    }
    return rafStream;
}
 
Example 7
Project: GitHub   File: JfifUtil.java   View Source Code Vote up 5 votes
/**
 *  Reads the content of the input stream until specified marker is found. Marker will be
 *  consumed and the input stream will be positioned after the specified marker.
 *  @param is the input stream to read bytes from
 *  @param markerToFind the marker we are looking for
 *  @return boolean: whether or not we found the expected marker from input stream.
 */
public static boolean moveToMarker(InputStream is, int markerToFind) throws IOException {
  Preconditions.checkNotNull(is);
  // ISO/IEC 10918-1:1993(E)
  while (StreamProcessor.readPackedInt(is, 1, false) == MARKER_FIRST_BYTE) {
    int marker = MARKER_FIRST_BYTE;
    while (marker == MARKER_FIRST_BYTE) {
      marker = StreamProcessor.readPackedInt(is, 1, false);
    }

    if (markerToFind == MARKER_SOFn && isSOFn(marker)) {
      return true;
    }
    if (marker == markerToFind) {
      return true;
    }

    // Check if the marker is SOI or TEM. These two don't have length field, so we skip it.
    if (marker == MARKER_SOI || marker == MARKER_TEM) {
      continue;
    }

    // Check if the marker is EOI or SOS. We will stop reading since metadata markers don't
    // come after these two markers.
    if (marker == MARKER_EOI || marker == MARKER_SOS) {
      return false;
    }

    // read block length
    // subtract 2 as length contain SIZE field we just read
    int length = StreamProcessor.readPackedInt(is, 2, false) - 2;
    // Skip other markers.
    is.skip(length);
  }
  return false;
}
 
Example 8
Project: GitHub   File: WebpUtil.java   View Source Code Vote up 5 votes
/**
 * We manage the Simple WebP case
 *
 * @param is The InputStream we're reading
 * @return The dimensions if any
 * @throws IOException In case or error reading from the InputStream
 */
private static Pair<Integer, Integer> getVP8Dimension(final InputStream is) throws IOException {
  // We need to skip 7 bytes
  is.skip(7);
  // And then check the signature
  final short sign1 = getShort(is);
  final short sign2 = getShort(is);
  final short sign3 = getShort(is);
  if (sign1 != 0x9D || sign2 != 0x01 || sign3 != 0x2A) {
    // Signature error
    return null;
  }
  // We read the dimensions
  return new Pair<>(get2BytesAsInt(is), get2BytesAsInt(is));
}
 
Example 9
Project: MetadataEditor   File: EncodingChunkReader.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */
public Chunk read(final GUID guid, final InputStream stream, final long chunkStart) throws IOException
{
    final BigInteger chunkLen = Utils.readBig64(stream);
    final EncodingChunk result = new EncodingChunk(chunkLen);
    int readBytes = 24;
    // Can't be interpreted
    /*
     * What do I think of this data, well it seems to be another GUID. Then
     * followed by a UINT16 indicating a length of data following (by half).
     * My test files just had the length of one and a two bytes zero.
     */
    stream.skip(20);
    readBytes += 20;

    /*
     * Read the number of strings which will follow
     */
    final int stringCount = Utils.readUINT16(stream);
    readBytes += 2;

    /*
     * Now reading the specified amount of strings.
     */
    for (int i = 0; i < stringCount; i++)
    {
        final String curr = Utils.readCharacterSizedString(stream);
        result.addString(curr);
        readBytes += 4 + 2 * curr.length();
    }
    stream.skip(chunkLen.longValue() - readBytes);
    result.setPosition(chunkStart);
    return result;
}
 
Example 10
Project: microbit   File: HexInputStream.java   View Source Code Vote up 5 votes
private long skip(final InputStream in, final long offset) throws IOException {
      long skipped = in.skip(offset);
int attempts = 10;
      // try to skip 10 times as skip(..) method does not guarantee to skip exactly given number of bytes
      while (skipped < offset && attempts > 0) {
	skipped += in.skip(offset - skipped);
	attempts--;
}
      return skipped;
  }
 
Example 11
Project: PokeData   File: Lz77.java   View Source Code Vote up 5 votes
public static int[] decompress(ROM rom, int offset) {
    InputStream stream = new ByteArrayInputStream(rom.getData());
    HexInputStream hexStream = new HexInputStream(stream);

    try {
        stream.skip(offset);

        return CompressUtils.decompress(hexStream);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 12
Project: openjdk-jdk10   File: Skip.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    try
    {
        setUp();

        for (int i = 0; i < 8; i++) {
            ModelByteBuffer buff;
            if(i % 2 == 0)
                buff = new ModelByteBuffer(test_file);
            else
                buff = new ModelByteBuffer(test_byte_array);
            if((i / 2) == 1)
                buff.subbuffer(5);
            if((i / 2) == 2)
                buff.subbuffer(5,500);
            if((i / 2) == 3)
                buff.subbuffer(5,600,true);

            long capacity = buff.capacity();
            InputStream is = buff.getInputStream();
            try
            {
                int ret = is.available();
                long n = is.skip(75);
                if(n == -1)
                    throw new RuntimeException("is.read shouldn't return -1!");
                if(is.available() != ret - n)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret - n)+") !");

                ret = is.available();
                n = is.skip(-100);
                if(n != 0)
                    throw new RuntimeException("is.skip(-100) shouldn't skip values!");
                if(is.available() != ret - n)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret - n)+") !");

                ret = is.available();
                n = is.skip(5000);
                if(is.available() != ret - n)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret - n)+") !");
                if(is.available() != 0)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(0)+") !");                }
            finally
            {
                is.close();
            }
            if(buff.capacity() != capacity)
                throw new RuntimeException("Capacity variable should not change!");
        }
    }
    finally
    {
        tearDown();
    }
}
 
Example 13
Project: GitHub   File: Streams.java   View Source Code Vote up 4 votes
public static void skipAll(InputStream in) throws IOException {
    do {
        in.skip(Long.MAX_VALUE);
    } while (in.read() != -1);
}
 
Example 14
Project: LoRaWAN-Smart-Parking   File: Util.java   View Source Code Vote up 4 votes
public static void skipAll(InputStream in) throws IOException {
  do {
    in.skip(Long.MAX_VALUE);
  } while (in.read() != -1);
}
 
Example 15
Project: jdk8u-jdk   File: MarkReset.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    try
    {
        setUp();

        for (int i = 0; i < 8; i++) {
            ModelByteBuffer buff;
            if(i % 2 == 0)
                buff = new ModelByteBuffer(test_file);
            else
                buff = new ModelByteBuffer(test_byte_array);
            if((i / 2) == 1)
                buff.subbuffer(5);
            if((i / 2) == 2)
                buff.subbuffer(5,500);
            if((i / 2) == 3)
                buff.subbuffer(5,600,true);

            long capacity = buff.capacity();
            InputStream is = buff.getInputStream();
            try
            {
                is.mark(1000);
                int ret = is.available();
                int a = is.read();
                is.skip(75);
                is.reset();
                if(is.available() != ret)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret)+") !");
                int b = is.read();
                if(a != b)
                    throw new RuntimeException(
                            "is doesn't return same value after reset ("
                            + a + "!="+b+") !");

                is.skip(15);
                ret = is.available();
                is.mark(1000);
                is.reset();
                if(is.available() != ret)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret)+") !");


            }
            finally
            {
                is.close();
            }
            if(buff.capacity() != capacity)
                throw new RuntimeException("Capacity variable should not change!");
        }
    }
    finally
    {
        tearDown();
    }
}
 
Example 16
Project: EatDubbo   File: StreamUtils.java   View Source Code Vote up 4 votes
public static void skipUnusedStream(InputStream is) throws IOException {
    if (is.available() > 0) {
        is.skip(is.available());
    }
}
 
Example 17
Project: GitHub   File: ResponseCacheTest.java   View Source Code Vote up 4 votes
private void reliableSkip(InputStream in, int length) throws IOException {
  while (length > 0) {
    length -= in.skip(length);
  }
}
 
Example 18
Project: quorrabot   File: HTTPSServer.java   View Source Code Vote up 4 votes
public void handle(HttpExchange httpExchange) throws IOException {
    HttpsExchange exchange = (HttpsExchange) httpExchange;
    Boolean hasPassword = false;
    String myPassword = "";
    String myHdrUser = "";
    String myHdrMessage = "";
    String[] uriQueryList = null;

    // Get the path and query string from the URI
    URI uriData = exchange.getRequestURI();
    String uriPath = uriData.getPath();
    String uriQuery = uriData.getQuery();

    if (uriQuery != null) {
        uriQueryList = uriQuery.split("&");
    }

    // Get the headers
    Headers headers = exchange.getRequestHeaders();

    // Get the Request Method (GET/PUT)
    String requestMethod = exchange.getRequestMethod();

    // Get any data from the body, although, we just discard it, this is required
    InputStream inputStream = exchange.getRequestBody();
    while (inputStream.read() != -1) {
        inputStream.skip(0x10000);
    }
    inputStream.close();

    if (headers.containsKey("password")) {
        myPassword = headers.getFirst("password");
        if (myPassword.equals(serverPassword) || myPassword.equals("oauth:" + serverPassword)) {
            hasPassword = true;
        }
    }
    if (headers.containsKey("webauth")) {
        myPassword = headers.getFirst("webauth");
        if (myPassword.equals(serverWebAuth)) {
            hasPassword = true;
        }
    }
    if (headers.containsKey("user")) {
        myHdrUser = headers.getFirst("user");
    }
    if (headers.containsKey("message")) {
        myHdrMessage = headers.getFirst("message");
    }

    if (requestMethod.equals("GET")) {
        if (uriPath.contains("..")) {
            sendHTMLError(403, "Invalid URL", exchange);
        } else if (uriPath.startsWith("/inistore")) {
            handleIniStore(uriPath, exchange, hasPassword);
        } else if (uriPath.startsWith("/dbquery")) {
            handleDBQuery(uriPath, uriQueryList, exchange, hasPassword);
        } else if (uriPath.startsWith("/addons") || uriPath.startsWith("/logs")) {
            handleFile(uriPath, exchange, hasPassword, true);
        } else if (uriPath.equals("/playlist")) {
            handleFile("/web/playlist/index.html", exchange, hasPassword, false);
        } else if (uriPath.equals("/")) {
            handleFile("/web/index.html", exchange, hasPassword, false);
        } else {
            handleFile("/web" + uriPath, exchange, hasPassword, false);
        }
    }

    if (requestMethod.equals("PUT")) {
        handlePutRequest(myHdrUser, myHdrMessage, exchange, hasPassword);
    }

}
 
Example 19
Project: util   File: StreamUtils.java   View Source Code Vote up 4 votes
/**
 * Copy a range of content of the given InputStream to the given
 * OutputStream.
 * <p>
 * If the specified range exceeds the length of the InputStream, this copies
 * up to the end of the stream and returns the actual number of copied
 * bytes.
 * <p>
 * Leaves both streams open when done.
 * 
 * @param in
 *            the InputStream to copy from
 * @param out
 *            the OutputStream to copy to
 * @param start
 *            the position to start copying from
 * @param end
 *            the position to end copying
 * @return the number of bytes copied
 * @throws IOException
 *             in case of I/O errors
 * @since 4.3
 */
public static long copyRange(InputStream in, OutputStream out, long start, long end) throws IOException {
	long skipped = in.skip(start);
	if (skipped < start) {
		throw new IOException("Skipped only " + skipped + " bytes out of " + start + " required.");
	}
	long bytesToCopy = end - start + 1;
	byte buffer[] = new byte[StreamUtils.BUFFER_SIZE];
	while (bytesToCopy > 0) {
		int bytesRead = in.read(buffer);
		if (bytesRead == -1) {
			break;
		} else if (bytesRead <= bytesToCopy) {
			out.write(buffer, 0, bytesRead);
			bytesToCopy -= bytesRead;
		} else {
			out.write(buffer, 0, (int) bytesToCopy);
			bytesToCopy = 0;
		}
	}
	return end - start + 1 - bytesToCopy;
}
 
Example 20
Project: guava-mock   File: ByteStreams.java   View Source Code Vote up 2 votes
/**
 * Attempts to skip up to {@code n} bytes from the given input stream, but not more than
 * {@code in.available()} bytes. This prevents {@code FileInputStream} from skipping more bytes
 * than actually remain in the file, something that it {@linkplain
 * java.io.FileInputStream#skip(long) specifies} it can do in its Javadoc despite the fact that
 * it is violating the contract of {@code InputStream.skip()}.
 */
private static long skipSafely(InputStream in, long n) throws IOException {
  int available = in.available();
  return available == 0 ? 0 : in.skip(Math.min(available, n));
}