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

The following examples show how to use java.io.InputStream#available() . These examples are extracted from open source projects. 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
/**
 * Inserts a procedure into the data store from a resource id
 *
 * @param ctx the Context where the data is stored
 * @param id  the raw resource id
 */
private static void insertProcedureFromResourceId(Context ctx, int id) {
    try {
        InputStream rs = ctx.getResources().openRawResource(id);
        byte[] data = new byte[rs.available()];
        rs.read(data);

        String xmlFullProcedure = new String(data);
        Procedure procedure = Procedure.fromXMLString(xmlFullProcedure);
        insertProcedure(procedure, xmlFullProcedure, ctx);
    } catch (Exception e) {
        Log.e(TAG, "Couldn't add procedure with resource id=" + id
                + " to db. Exception : " + e.toString());
        e.printStackTrace();
    }
}
 
Example 2
Source Project: bboxdb   File: CompressionHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
/**
 * Handle compressed packages. Uncompress envelope and handle package
 */
public boolean handleRequest(final ByteBuffer encodedPackage, 
		final short packageSequence, final ClientConnectionHandler clientConnectionHandler) {
	
	try {
		final InputStream compressedDataStream = CompressionEnvelopeRequest.decodePackage(encodedPackage);
					
		while(compressedDataStream.available() > 0) {
			clientConnectionHandler.handleNextPackage(compressedDataStream);
		}
		
	} catch (IOException | PackageEncodeException e) {
		logger.error("Got an exception while handling compression", e);
	} 
	
	return true;
}
 
Example 3
Source Project: jrpip   File: BlockInputStream.java    License: Apache License 2.0 6 votes vote down vote up
private void fillAvailable(InputStream in, long lenLeft) throws IOException
{
    if (lenLeft < leftToCopy())
    {
        return;
    }
    int localSpace = leftToFill();
    if (localSpace == 0)
    {
        return;
    }
    int avail = in.available();
    if (avail == 0)
    {
        avail = 128;
    }
    int toFill = Math.min(localSpace, avail);
    fullyRead(in, this.buf, this.lengthRead, toFill);
    this.lengthRead += toFill;
}
 
Example 4
/**
 * Make a byte buffer from an input stream.
 */
public ByteBuffer makeByteBuffer(InputStream in)
    throws IOException {
    int limit = in.available();
    if (limit < 1024) limit = 1024;
    ByteBuffer result = byteBufferCache.get(limit);
    int position = 0;
    while (in.available() != 0) {
        if (position >= limit)
            // expand buffer
            result = ByteBuffer.
                allocate(limit <<= 1).
                put((ByteBuffer)result.flip());
        int count = in.read(result.array(),
            position,
            limit - position);
        if (count < 0) break;
        result.position(position += count);
    }
    return (ByteBuffer)result.flip();
}
 
Example 5
Source Project: libcommon   File: SysFs.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] readBytes(@Nullable final String name) throws IOException {
	byte[] result;
	mReadLock.lock();
	try {
		final byte[] buf = new byte[512];
		final MyByteArrayOutputStream out = new MyByteArrayOutputStream(1024);
		final InputStream in = new BufferedInputStream(new FileInputStream(getPath(name)));
		try {
			int available = in.available();
			for (; available > 0; ) {
				final int bytes = in.read(buf);
				if (bytes > 0) {
					out.write(buf, 0, bytes);
				}
				available = in.available();
			}
			result = out.toByteArray();
		} finally {
			in.close();
		}
	} finally {
		mReadLock.unlock();
	}
	return result;
}
 
Example 6
/**
 * Copies all the bytes from this input into this buffer.
 *
 * @param in input stream.
 * @exception IOException in case of an I/O error.
 */
public void write(InputStream in) throws IOException {
    if (in instanceof ByteArrayInputStream) {
        int size = in.available();
        ensureCapacity(size);
        count += in.read(buf,count,size);
        return;
    }
    while(true) {
        int cap = buf.length-count;
        int sz = in.read(buf,count,cap);
        if(sz<0)    return;     // hit EOS

        count += sz;
        if(cap==sz)
            // the buffer filled up. double the buffer
            ensureCapacity(count);
    }
}
 
Example 7
public static void copyResource(Context context, int resID, File destination) 
{
	InputStream is = context.getResources().openRawResource(resID);
       try
       {
           byte[] buffer = new byte[is.available()];
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destination));

        int l = 0;
        while((l = is.read(buffer)) > 0)
        {
            bos.write(buffer, 0, l);
        }
        bos.close();
       } 
       catch(IOException e)
       {
       	throw new Error(e);
       }
}
 
Example 8
Source Project: SimplicityBrowser   File: CSSInjection.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
private static void instagramLight(Context context, WebView view) {
    try {
        InputStream inputStream = context.getAssets().open("instagram.css");
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
        view.loadUrl("javascript:(function() {" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var style = document.createElement('style');" +
                "style.type = 'text/css';" +
                "style.innerHTML = window.atob('" + encoded + "');" +
                "parent.appendChild(style)" +
                "})()");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source Project: Mupdf   File: StreamUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从输入流里面读出每行文字
 */
public static ArrayList<String> loadStringLinesFromStream(InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in, "UTF-8");
    BufferedReader br = new BufferedReader(reader);
    String row;
    ArrayList<String> lines = new ArrayList<String>();
    int length = in.available();
    try {
        while ((row = br.readLine()) != null) {
            lines.add(row);
        }
    } catch (OutOfMemoryError e) {

    }
    br.close();
    reader.close();
    return lines;
}
 
Example 10
Source Project: TelegramApi   File: MTRpcResult.java    License: MIT License 5 votes vote down vote up
@Override
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
    this.messageId = readLong(stream);
    int contentSize = stream.available();
    this.content = BytesCache.getInstance().allocate(contentSize);
    readBytes(this.content, 0, contentSize, stream);
}
 
Example 11
Source Project: AIBot   File: Main.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void printTC(){
	InputStream in = Main.class.getClassLoader().getResourceAsStream("tc.txt");
	byte[] b;
	try {
		b = new byte[in.available()];
		in.read(b, 0, b.length);
		System.out.println(new String(b, Charset.forName("UTF8")));
	} catch (IOException e) {
		//e.printStackTrace();
		return;
	}
	
}
 
Example 12
/**
 * Create a new stream to decode OGG data
 * 
 * @param input The input stream from which to read the OGG file
 * @throws IOException Indicates a failure to read from the supplied stream
 */
public OggInputStream(InputStream input) throws IOException {
	this.input = input;
	total = input.available();
	
	init();
}
 
Example 13
Source Project: centrifuge-java   File: Client.java    License: MIT License 5 votes vote down vote up
private void handleConnectionMessage(byte[] bytes) {
    if (this.disconnecting) {
        return;
    }
    InputStream stream = new ByteArrayInputStream(bytes);
    try {
        while (stream.available() > 0) {
            Protocol.Reply reply = Protocol.Reply.parseDelimitedFrom(stream);
            this.processReply(reply);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Source Project: Geyser   File: LoopbackUtil.java    License: MIT License 5 votes vote down vote up
public static void checkLoopback(GeyserStandaloneLogger geyserLogger) {
    if (System.getProperty("os.name").equalsIgnoreCase("Windows 10")) {
        try {
            Process process = Runtime.getRuntime().exec(checkExemption);
            InputStream is = process.getInputStream();
            StringBuilder sb = new StringBuilder();

            while (process.isAlive()) {
                if (is.available() != 0) {
                    sb.append((char) is.read());
                }
            }

            String result = sb.toString();

            if (!result.contains("minecraftuwp")) {
                Files.write(Paths.get(System.getenv("temp") + "/loopback_minecraft.bat"), loopbackCommand.getBytes(), new OpenOption[0]);
                process = Runtime.getRuntime().exec(startScript);

                geyserLogger.info(ChatColor.AQUA + "Added loopback exemption to Windows!");
            }
        } catch (Exception e) {
            e.printStackTrace();

            geyserLogger.error("Couldn't auto add loopback exemption to Windows!");
        }
    }
}
 
Example 15
public static byte[] readBytes(Context context, Uri fileUri) {
    try {
        InputStream fis = context.getContentResolver().openInputStream(fileUri);
        int len = fis.available();
        byte[] buffer = new byte[len];
        fis.read(buffer);
        fis.close();
        return buffer;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 16
/**
 * This copies the downloaded data from the InputStream to the OutputStream,
 * keeping track of the number of bytes that have flowed through for the
 * progress counter.
 */
private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)
        throws IOException, InterruptedException {
    Timer timer = new Timer();
    try {
        bytesRead = 0;
        totalBytes = totalDownloadSize();
        byte[] buffer = new byte[bufferSize];

        timer.scheduleAtFixedRate(progressTask, 0, 100);

        // Getting the total download size could potentially take time, depending on how
        // it is implemented, so we may as well check this before we proceed.
        throwExceptionIfInterrupted();

        while (true) {

            int count;
            if (input.available() > 0) {
                int readLength = Math.min(input.available(), buffer.length);
                count = input.read(buffer, 0, readLength);
            } else {
                count = input.read(buffer);
            }

            throwExceptionIfInterrupted();

            if (count == -1) {
                Utils.debugLog(TAG, "Finished downloading from stream");
                break;
            }
            bytesRead += count;
            output.write(buffer, 0, count);
        }
    } finally {
        downloaderProgressListener = null;
        timer.cancel();
        timer.purge();
        output.flush();
        output.close();
    }
}
 
Example 17
Source Project: EasyHttp   File: UpdateBody.java    License: Apache License 2.0 4 votes vote down vote up
public UpdateBody(InputStream inputStream, String name) throws IOException {
    this(Okio.source(inputStream), MEDIA_TYPE, name, inputStream.available());
}
 
Example 18
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
            {
                byte[] b = new byte[100];
                int ret = is.available();
                int n = is.read(b);
                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)+") !");
                is.skip(5000);
                if(is.read(b) != -1)
                    throw new RuntimeException(
                            "is.read() doesn't return -1!");

            }
            finally
            {
                is.close();
            }
            if(buff.capacity() != capacity)
                throw new RuntimeException("Capacity variable should not change!");
        }
    }
    finally
    {
        tearDown();
    }
}
 
Example 19
Source Project: jdk8u-dev-jdk   File: Read.java    License: 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
            {
                byte[] b = new byte[100];
                int ret = is.available();
                int n = is.read();
                if(n == -1)
                    throw new RuntimeException("is.read shouldn't return -1!");
                if(is.available() != ret - 1)
                    throw new RuntimeException(
                            "is.available() returns incorrect value ("
                            + is.available() + "!="+(ret - 1)+") !");
                is.skip(5000);
                if(is.read() != -1)
                    throw new RuntimeException(
                            "is.read() doesn't return -1!");
            }
            finally
            {
                is.close();
            }
            if(buff.capacity() != capacity)
                throw new RuntimeException("Capacity variable should not change!");
        }
    }
    finally
    {
        tearDown();
    }
}
 
Example 20
Source Project: birt   File: PDFImageLM.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/**
 * get intrinsic dimension of image in pixels. Now only support png, bmp,
 * jpg, gif.
 * 
 * @param in
 * @return
 * @throws IOException
 * @throws MalformedURLException
 * @throws BadElementException
 */
protected Dimension getIntrinsicDimension( IImageContent content )
		throws BadElementException, MalformedURLException, IOException
{
	Image image = null;
	switch ( content.getImageSource( ) )
	{
		case IImageContent.IMAGE_FILE :
			ReportDesignHandle design = content.getReportContent( )
					.getDesign( ).getReportDesign( );
			URL url = design.findResource( content.getURI( ),
					IResourceLocator.IMAGE, content.getReportContent( )
							.getReportContext( ) == null ? null : content
							.getReportContent( ).getReportContext( )
							.getAppContext( ) );
			InputStream in = url.openStream( );
			try
			{
				byte[] buffer = new byte[in.available( )];
				in.read( buffer );
				image = Image.getInstance( buffer );
			}
			catch ( Exception ex )
			{
				logger.log( Level.WARNING, ex.getMessage( ), ex );
			}
			finally
			{
				in.close( );
			}
			break;
		case IImageContent.IMAGE_NAME :
		case IImageContent.IMAGE_EXPRESSION :
			image = Image.getInstance( content.getData( ) );
			break;

		case IImageContent.IMAGE_URL :
			image = Image.getInstance( new URL( content.getURI( ) ) );
			break;
		default :
			assert ( false );
	}
	if ( image != null )
	{
		int resolution = 96;
		int contentResolution = content.getResolution( );
		if ( contentResolution != 0 )
		{
			resolution = contentResolution;
		}
		return new Dimension( (int) ( image.getPlainWidth( ) * 1000
				/ resolution * 72 ), (int) ( image.getPlainHeight( ) * 1000
				/ resolution * 72 ) );
	}
	return null;
}