Java bufferedinputstream to byte array

Class BufferedInputStream

A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods. When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.

Field Summary

The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail.

Fields declared in class java.io.FilterInputStream

Constructor Summary

Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in , for later use.

Method Summary

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Methods declared in class java.io.FilterInputStream

Methods declared in class java.io.InputStream

Methods declared in class java.lang.Object

Field Details

buf

The internal buffer array where the data is stored. When necessary, it may be replaced by another array of a different size.

count

The index one greater than the index of the last valid byte in the buffer. This value is always in the range 0 through buf.length ; elements buf[0] through buf[count-1] contain buffered input data obtained from the underlying input stream.

pos

The current position in the buffer. This is the index of the next character to be read from the buf array. This value is always in the range 0 through count . If it is less than count , then buf[pos] is the next byte to be supplied as input; if it is equal to count , then the next read or skip operation will require more bytes to be read from the contained input stream.

markpos

The value of the pos field at the time the last mark method was called. This value is always in the range -1 through pos . If there is no marked position in the input stream, this field is -1 . If there is a marked position in the input stream, then buf[markpos] is the first byte to be supplied as input after a reset operation. If markpos is not -1 , then all bytes from positions buf[markpos] through buf[pos-1] must remain in the buffer array (though they may be moved to another place in the buffer array, with suitable adjustments to the values of count , pos , and markpos ); they may not be discarded unless and until the difference between pos and markpos exceeds marklimit .

Читайте также:  Pip install python imaging

marklimit

The maximum read ahead allowed after a call to the mark method before subsequent calls to the reset method fail. Whenever the difference between pos and markpos exceeds marklimit , then the mark may be dropped by setting markpos to -1 .

Constructor Details

BufferedInputStream

Creates a BufferedInputStream and saves its argument, the input stream in , for later use. An internal buffer array is created and stored in buf .

BufferedInputStream

Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in , for later use. An internal buffer array of length size is created and stored in buf .

Method Details

read

read

  • The specified number of bytes have been read,
  • The read method of the underlying stream returns -1 , indicating end-of-file, or
  • The available method of the underlying stream returns zero, indicating that further input requests would block.

Subclasses of this class are encouraged, but not required, to attempt to read as many bytes as possible in the same fashion.

skip

available

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. This method returns the sum of the number of bytes remaining to be read in the buffer ( count — pos ) and the result of calling the in .available() .

mark

reset

See the general contract of the reset method of InputStream . If markpos is -1 (no mark has been set or the mark has been invalidated), an IOException is thrown. Otherwise, pos is set equal to markpos .

markSupported

Tests if this input stream supports the mark and reset methods. The markSupported method of BufferedInputStream returns true .

close

Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Читайте также:  Php write binary files

Источник

How to convert an input stream to byte array in java?

The InputStream class in Java provides read() method. This method accepts a byte array and it reads the contents of the input stream to the given byte array.

Example

import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; public class StreamToByteArray < public static void main(String args[]) throws IOException< InputStream is = new BufferedInputStream(System.in); byte [] byteArray = new byte[1024]; System.out.println("Enter some data"); is.read(byteArray); String s = new String(byteArray); System.out.println("Contents of the byte stream are :: "+ s); >>

Output

Enter some data hello how are you Contents of the byte stream are :: hello how are you

Alternative Solution

Apache commons provides a library named org.apache.commons.io and, following is the maven dependency to add library to your project.

This package provides a class known as IOUtils. the toByteArray () method of this class accepts an InputStream object and returns the contents in the stream in the form of a byte array:

Example

import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.io.IOUtils; public class StreamToByteArray2IOUtils < public static void main(String args[]) throws IOException< File file = new File("data"); FileInputStream fis = new FileInputStream(file); byte [] byteArray = IOUtils.toByteArray(fis); String s = new String(byteArray); System.out.println("Contents of the byte stream are :: "+ s); >>

Output

Contents of the byte stream are :: hello how are you

Источник

How to Convert InputStream to byte[]

This article illustrates different ways to Convert InputStream to a byte[] (or Byte Array) using Apache Common IO, Guava, and Plain Java.

Overview

The InputStream is a byte stream, which we read from almost anything in Java. Many ways are available to convert an InputStream to a byte[] or a ByteBuffer. In this tutorial, we will cover them one by one.

Before we do that, let’s quickly have a look at how to create an InputStream instance from a byte[] (Byte Array)

Converting a Byte Array to an InputStream

Let’s see a simple example of converting a byte[] to an InputStream in plain Java. We create a byte[] instance from a String object and use it to create an instance of the ByteArrayInputStream, a subclass of InputStream.

byte[] bytes = string.getBytes(UTF_8); InputStream inputStream = new ByteArrayInputStream(bytes);Code language: Java (java)

In the next part, we will see various ways of Converting an InputStream to a byte[].

InputStream to Byte Array Using Apache Commons IO

The Apache Commons IO Library provides many useful abstractions for basic File IO operations in Java. Next is a very simple and short way of creating byte[] from an InputStream.

Читайте также:  Php static class field

Example of using Apache Commons IO to convert an InputStream to byte[]

byte[] bytes = IOUtils .toByteArray(inputStream);Code language: Java (java)

InputStream to Byte Array Using Guava Library

Similarly, the Guava Library also provides a simple and concise way. We can use the ByteStreams utility class, as shown in the following example. The toByteArray() method returns a byte[] containing all the bytes from the given InputStream.
Example of using Guava to convert an InputStream to byte[]

byte[] bytes = ByteStreams .toByteArray(inputStream);Code language: Java (java)

InputStream to Byte Array Using Plain Java

The Java InputStream provides the read(byte[]) method, which copies all available bytes into the provided array of bytes. However, to use this method, we need to provide an array of the exact size.

And to do that, we read the number of available bytes from the InputStream instance and initialize a byte[] of the same size.

Example of using plain Java to convert an InputStream to a byte[].

int size = inputStream.available(); byte[] bytes = new byte[size]; inputStream.read(bytes);Code language: Java (java)

This solution works for an InputStream of a fixed size. However, if the InputStream is a BufferedInputStream, the available() method returns the current buffer size and not the size of all bytes.

For such a BufferedInputStream instance, we can use the readAllBytes() method that returns the size of all bytes.

byte[] bytes = inputStream.readAllBytes();Code language: Java (java)

InputStream to ByteArray Manually

We saw several ways of converting an InputStream to a Byte Array, and they used different abstractions to simplify the process. However, if we want more control over the size of the buffer and the amount of memory being used, we can do the conversion manually.

We can iteratively read a fixed number of bytes from the InputStream instance and consume them before reading the next set of bytes.

Example of converting an InputSteram to byte[] manually.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] bucket = new byte[1024]; int nReadBytes; while((nReadBytes = inputStream .read(bucket, 0, bucket.length)) !=-1)< byteArrayOutputStream.write(bucket, 0, nReadBytes); > byte[] bytes = byteArrayOutputStream.toByteArray();Code language: Java (java)

Firstly, we create an instance of the ByteArrayOutputStream, which is the consumer of our byte[]. Next, we make a byte[] bucket of a fixed size. During each iteration, we fill the bucket (of fixed size) from the InputStream and write it onto the ByteArrayOutputStream. And continue to do so until no more byes are left in the InputStream.

Summary

In this short tutorial, we covered different ways of Converting an InputStream to an array of bytes. We covered examples of using Apache Commons IO Library, Guava Library, and a couple of examples using Core Java. For more on Java, please visit Java Tutorials.

Please refer to our GitHub Repository for the complete source code of the examples.

Источник

Оцените статью