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

The following examples show how to use java.io.InputStream#skip() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StreamReader.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
protected void drain(InputStream dis, long bytesRead) throws IOException
{
    long toSkip = totalSize() - bytesRead;

    // InputStream.skip can return -1 if dis is inaccessible.
    long skipped = dis.skip(toSkip);
    if (skipped == -1)
        return;

    toSkip = toSkip - skipped;
    while (toSkip > 0)
    {
        skipped = dis.skip(toSkip);
        if (skipped == -1)
            break;
        toSkip = toSkip - skipped;
    }
}
 
Example 2
Source File: ByteCodeClassScanner.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses a method entry.
 */
private void scanMethod(InputStream is)
  throws IOException
{
  /*
  int accessFlags = readShort();
  int nameIndex = readShort();
  int descriptorIndex = readShort();
  */
  
  is.skip(6);

  int attributesCount = readShort(is);
  
  for (int i = 0; i < attributesCount; i++) {
    scanAttributeForAnnotation(is);
  }
}
 
Example 3
Source File: TiffUtil.java    From fresco with MIT License 6 votes vote down vote up
/**
 * 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 4
Source File: BootZipScanner.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
public static void skipLocalHeader(InputStream is)
  throws IOException
{
  int magic;

  if ((magic = readInt(is)) != 0x04034b50) {
    throw new IOException("invalid zip format "+ Integer.toHexString(magic));
  }
  
  is.skip(2 + 2 + 2 + 2 + 2 + 4 + 4 + 4);
  
  int nameLen = readShort(is);
  int extraLen = readShort(is);
  
  is.skip(nameLen + extraLen);
}
 
Example 5
Source File: LocationRetriever.java    From AppleWifiNlpBackend with Apache License 2.0 6 votes vote down vote up
public Collection<Location> retrieveLocations(String... macs) throws IOException {
    Request request = createRequest(macs);
    byte[] byteb = request.toByteArray();
    byte[] bytes = combineBytes(APPLE_MAGIC_BYTES, byteb, (byte) byteb.length);
    HttpsURLConnection connection = createConnection();
    prepareConnection(connection, bytes.length);
    OutputStream out = connection.getOutputStream();
    out.write(bytes);
    out.flush();
    out.close();
    InputStream in = connection.getInputStream();
    in.skip(10);
    Response response = wire.parseFrom(readStreamToEnd(in), Response.class);
    in.close();
    Collection<Location> locations = new ArrayList<Location>();
    for (Response.ResponseWifi wifi : response.wifis) {
        locations.add(fromResponseWifi(wifi));
    }
    return locations;
}
 
Example 6
Source File: LocalFilesystem.java    From jpHolo with MIT License 6 votes vote down vote up
@Override
   public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
		ReadFileCallback readFileCallback) throws IOException {

	File file = new File(this.filesystemPathForURL(inputURL));
       String contentType = FileHelper.getMimeTypeForExtension(file.getAbsolutePath());
	
       if (end < 0) {
           end = file.length();
       }
       long numBytesToRead = end - start;

       InputStream rawInputStream = new FileInputStream(file);
	try {
		if (start > 0) {
               rawInputStream.skip(start);
		}
           LimitedInputStream inputStream = new LimitedInputStream(rawInputStream, numBytesToRead);
           readFileCallback.handleData(inputStream, contentType);
	} finally {
           rawInputStream.close();
	}
}
 
Example 7
Source File: InputStreamUtils.java    From util4j with Apache License 2.0 5 votes vote down vote up
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 8
Source File: LogbackLogManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Nullable
@Guarded(by = STARTED)
public InputStream getLogFileStream(final String fileName, final long from, final long count) throws IOException {
  log.debug("Retrieving log file: {}", fileName);

  // checking for platform or normalized path-separator (on unix these are the same)
  if (fileName.contains(File.pathSeparator) || fileName.contains("/")) {
    log.warn("Cannot retrieve log files with path separators in their name");
    return null;
  }

  File file = getLogFile(fileName);
  if (file == null || !file.exists()) {
    log.warn("Log file does not exist: {}", fileName);
    return null;
  }

  long fromByte = from;
  long bytesCount = count;
  if (count < 0) {
    bytesCount = Math.abs(count);
    fromByte = Math.max(0, file.length() - bytesCount);
  }

  InputStream input = new BufferedInputStream(new FileInputStream(file));
  if (fromByte == 0 && bytesCount >= file.length()) {
    return input;
  }
  else {
    input.skip(fromByte);
    return ByteStreams.limit(input, bytesCount);
  }
}
 
Example 9
Source File: MergeStreamWithSortedSet.java    From database with GNU General Public License v2.0 5 votes vote down vote up
static public void process(final InputStream in, final Set<Entry<Long, byte[]>> snapshotData, final OutputStream out) throws IOException {
	
	final byte[] bb = new byte[4096];
	final Iterator<Entry<Long, byte[]>> bbs = snapshotData.iterator();
	
	long curs = 0;
	
	while (bbs.hasNext()) {
		final Entry<Long, byte[]> e = bbs.next();
		final long pos = e.getKey();
		final byte[] buf = e.getValue();
		final long blen = buf.length;
		
		// transfer Input to Output until start of buffer
		if (curs < pos) {
			transfer(in, (pos-curs), bb, out);
			
			curs = pos;
		}
		
		// transfer buffer
		out.write(buf);
		
		log.info("Write ByteBuffer at " + pos +", length: " + blen);
		
		curs += blen;
		
		// skip input over size of buffer
		in.skip(blen);
	}
	
	// Now transfer remainder of stream
	transfer(in, Long.MAX_VALUE, bb, out);
}
 
Example 10
Source File: DSSUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Skip the defined {@code n} number of bytes from the {@code InputStream}
 * and validates success of the operation
 * @param is {@link InputStream} to skip bytes from
 * @param n {@code long} number bytes to skip
 * @return actual number of bytes have been skipped
    * @exception IllegalStateException in case of {@code InputStream} reading error 
 */
public static long skipAvailableBytes(InputStream is, long n) throws IllegalStateException {
	try {
		long skipped = is.skip(n);
		if (skipped != n) {
			throw new IllegalStateException(String.format("The number of skipped bytes [%s] differs from the expected value [%s]! "
					+ "The InputStream is too small, corrupted or not accessible!", skipped, n));
		}
		return skipped;
	} catch (IOException e) {
		throw new DSSException("Cannot read the InputStream!", e);
	}
}
 
Example 11
Source File: MinimalZipParser.java    From archive-patcher with Apache License 2.0 5 votes vote down vote up
/**
 * Skips exactly the specified number of bytes, throwing an exception if unsuccessful.
 * @param in the stream to read from
 * @param numBytes the number of bytes to skip
 * @throws IOException if EOF is reached or no more bytes can be skipped
 */
private static void skipOrDie(InputStream in, long numBytes) throws IOException {
  long numLeft = numBytes;
  long numSkipped = 0;
  while ((numSkipped = in.skip(numLeft)) > 0) {
    numLeft -= numSkipped;
  }
  if (numLeft != 0) {
    throw new IOException("Unable to skip");
  }
}
 
Example 12
Source File: InputStreamBerDataValueReader.java    From Xpatch with Apache License 2.0 5 votes vote down vote up
private static void skipDefiniteLengthContents(InputStream in, int len)
        throws IOException, BerDataValueFormatException {
    long bytesRead = 0;
    while (len > 0) {
        int skipped = (int) in.skip(len);
        if (skipped <= 0) {
            throw new BerDataValueFormatException(
                    "Truncated definite-length contents: " + bytesRead + " bytes read"
                            + ", " + len + " missing");
        }
        len -= skipped;
        bytesRead += skipped;
    }
}
 
Example 13
Source File: ByteCodeClassScanner.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private void skipElementValue(InputStream is)
  throws IOException
{
  int code = is.read();

  switch (code) {
  case 'B': case 'C': case 'D': case 'F': case 'I': case 'J':
  case 'S': case 'Z': case 's':
    is.skip(2);
    return;
  case 'e':
    is.skip(4);
    return;
  case 'c':
    is.skip(2);
    return;
  case '@':
    scanAnnotation(is);
    return;
  case '[':
    int len = readShort(is);
    for (int i = 0; i < len; i++) {
      skipElementValue(is);
    }
    return;
  default:
    throw new IllegalStateException("unknown code: " + (char) code);
  }
}
 
Example 14
Source File: RedissonBinaryStreamTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testSkip() throws IOException {
    RBinaryStream t = redisson.getBinaryStream("test");
    t.set(new byte[] {1, 2, 3, 4, 5, 6});
    
    InputStream is = t.getInputStream();
    is.skip(3);
    byte[] b = new byte[6];
    is.read(b);
    assertThat(b).isEqualTo(new byte[] {4, 5, 6, 0, 0, 0});
}
 
Example 15
Source File: MarkReset.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
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
Source File: SmbServerThread.java    From DanDanPlayForAndroid with MIT License 4 votes vote down vote up
private synchronized void dispatchResponse(HttpResponse response,
                                           HttpSocket httpSocket,
                                           long contentOffset,
                                           long contentLength,
                                           boolean badRequest) {
    printLog("----- dispatch http response -----");

    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        outputStream = httpSocket.getOutputStream();
        outputStream.write(response.getResponseHeader().getBytes());
        //必须返回!!!
        outputStream.write("\r\n".getBytes());

        //无法处理的请求
        if (badRequest) {
            outputStream.flush();
            printLog("----- return bad response -----");
            return;
        }

        inputStream = response.getContentInputStream();
        if (contentOffset > 0) {
            if (inputStream.skip(contentOffset) > 0) {
                printLog("----- input stream skip -----:" + contentOffset);
            }
        }

        int bufferSize = 512 * 1024;
        byte[] readBuffer = new byte[bufferSize];
        long readTotalSize = 0;
        long readSize = (bufferSize > contentLength) ? contentLength : bufferSize;
        int readLen = inputStream.read(readBuffer, 0, (int) readSize);

        printLog("----- send video data start -----:" + contentOffset);
        while (readLen > 0 && readTotalSize < contentLength) {
            outputStream.write(readBuffer, 0, readLen);
            outputStream.flush();
            readTotalSize += readLen;
            readSize = (bufferSize > (contentLength - readTotalSize))
                    ? (contentLength - readTotalSize)
                    : bufferSize;
            readLen = inputStream.read(readBuffer, 0, (int) readSize);

            printLog("----- send video data success -----:" + readTotalSize + "/" + contentLength);
        }
        printLog("----- send video data over -----:" + contentOffset);
        outputStream.flush();
    } catch (Exception e) {
        printLog("----- send video data error -----:" + e.getMessage());
        e.printStackTrace();
    } finally {
        try {if (inputStream != null)
            inputStream.close();
            if (outputStream != null)
                outputStream.close();
        }catch (IOException ignore){

        }
    }
}
 
Example 17
Source File: StreamUtils.java    From anima with GNU General Public License v3.0 4 votes vote down vote up
public static void skipUnusedStream(InputStream is) throws IOException {
    if (is.available() > 0) {
        is.skip(is.available());
    }
}
 
Example 18
Source File: MediaUtil.java    From message_interface with MIT License 4 votes vote down vote up
public static int[] querySize(InputStream is) throws IOException {
    int c1 = is.read();
    int c2 = is.read();
    int c3 = is.read();
    int width = 0;
    int height = 0;
    if (c1 == 'G' && c2 == 'I' && c3 == 'F') { // GIF
        is.skip(3);
        width = readInt(is,2,false);
        height = readInt(is,2,false);
    } else if (c1 == 0xFF && c2 == 0xD8) { // JPG
        while (c3 == 255) {
            int marker = is.read();
            int len = readInt(is,2,true);
            if (marker == 192 || marker == 193 || marker == 194) {
                is.skip(1);
                width = readInt(is,2,true);
                height = readInt(is,2,true);
                break;
            }
            is.skip(len - 2);
            c3 = is.read();
        }
    } else if (c1 == 137 && c2 == 80 && c3 == 78) { // PNG
        is.skip(15);
        width = readInt(is,2,true);
        is.skip(2);
        height = readInt(is,2,true);
    } else if (c1 == 66 && c2 == 77) { // BMP
        is.skip(15);
        width = readInt(is,2,false);
        is.skip(2);
        height = readInt(is,2,false);
    } else {
        int c4 = is.read();
        if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
                || (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) { //TIFF
            boolean bigEndian = c1 == 'M';
            int ifd = 0;
            int entries;
            ifd = readInt(is,4,bigEndian);
            is.skip(ifd - 8);
            entries = readInt(is,2,bigEndian);
            for (int i = 1; i <= entries; i++) {
                int tag = readInt(is,2,bigEndian);
                int fieldType = readInt(is,2,bigEndian);
                int valOffset;
                if ((fieldType == 3 || fieldType == 8)) {
                    valOffset = readInt(is,2,bigEndian);
                    is.skip(2);
                } else {
                    valOffset = readInt(is,4,bigEndian);
                }
                if (tag == 256) {
                    width = valOffset;
                } else if (tag == 257) {
                    height = valOffset;
                }
                if (width != -1 && height != -1) {
                    break;
                }
            }
        }
    }
    return new int[] {width, height};
}
 
Example 19
Source File: BoxRequestsFile.java    From box-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
protected void setBody(BoxHttpRequest request) throws IOException  {
    InputStream inputStream = getInputStream();
    //skip previous parts
    if (!mIsAlreadyPositioned) {
        long skipTo = ((long)mPartNumber) * mUploadSession.getPartSize();
        inputStream.skip(skipTo);
    }

    //Write bytes to URLConnection of the request
    URLConnection urlConnection = request.getUrlConnection();
    urlConnection.setDoOutput(true);
    OutputStream output = urlConnection.getOutputStream();
    if(mListener != null) {
        output = new ProgressOutputStream(output, mListener, getPartSize());
    }
    byte[] byteBuf = new byte[SdkUtils.BUFFER_SIZE];
    long totalBytesRead = 0;
    int bytesRead = 0;

    try {
        do {
            if (Thread.currentThread().isInterrupted()){
                throw new InterruptedException();
            }
            if (totalBytesRead + byteBuf.length > mCurrentChunkSize){
                bytesRead = inputStream.read(byteBuf, 0, (int)(totalBytesRead + byteBuf.length - mCurrentChunkSize));
            } else {
                bytesRead = inputStream.read(byteBuf, 0, byteBuf.length);
            }
            if (bytesRead != -1) {
                output.write(byteBuf, 0, bytesRead);
                totalBytesRead += bytesRead;
            }
        } while (bytesRead != -1 && totalBytesRead < mCurrentChunkSize);
    } catch (InterruptedException ie) {
        throw new IOException(ie);
    } finally {
        output.close();
        if (mFile != null || !mIsAlreadyPositioned){
            inputStream.close();
        }
    }
}
 
Example 20
Source File: Image.java    From MesquiteCore with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * This method is an alternative for the <CODE>InputStream.skip()</CODE>
 * -method that doesn't seem to work properly for big values of <CODE>size
 * </CODE>.
 * 
 * @param is
 *            the <CODE>InputStream</CODE>
 * @param size
 *            the number of bytes to skip
 * @throws IOException
 */

static public void skip(InputStream is, int size) throws IOException {
	while (size > 0) {
		size -= is.skip(size);
	}
}