Convert InputStream to byte array in Java
Convert InputStream to byte array in Java
How do I read an entire InputStream
into a byte array?
Answer by Adamski for Convert InputStream to byte array in Java
You need to read each byte from your InputStream
and write it to a ByteArrayOutputStream
. You can then retrieve the underlying byte array by calling toByteArray()
; e.g.
InputStream is = ... ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray();
Answer by Rich Seller for Convert InputStream to byte array in Java
You can use Apache Commons IO to handle this and similar tasks.
The IOUtils
type has a static method to read an InputStream
and return a byte[]
.
InputStream is; byte[] bytes = IOUtils.toByteArray(is);
Internally this creates a ByteArrayOutputStream
and copies the bytes to the output, then calls toByteArray()
. It handles large files by copying the bytes in blocks of 4KiB.
Answer by firstthumb for Convert InputStream to byte array in Java
Below Codes
public static byte[] serializeObj(Object obj) throws IOException { ByteArrayOutputStream baOStream = new ByteArrayOutputStream(); ObjectOutputStream objOStream = new ObjectOutputStream(baOStream); objOStream.writeObject(obj); objOStream.flush(); objOStream.close(); return baOStream.toByteArray(); }
OR
BufferedImage img = ... ByteArrayOutputStream baos = new ByteArrayOutputStream(1000); ImageIO.write(img, "jpeg", baos); baos.flush(); byte[] result = baos.toByteArray(); baos.close();
Answer by Jesper for Convert InputStream to byte array in Java
Do you really need the image as a byte[]
? What exactly do you expect in the byte[]
- the complete content of an image file, encoded in whatever format the image file is in, or RGB pixel values?
Other answers here show you how to read a file into a byte[]
. Your byte[]
will contain the exact contents of the file, and you'd need to decode that to do anything with the image data.
Java's standard API for reading (and writing) images is the ImageIO API, which you can find in the package javax.imageio
. You can read in an image from a file with just a single line of code:
BufferedImage image = ImageIO.read(new File("image.jpg"));
This will give you a BufferedImage
, not a byte[]
. To get at the image data, you can call getRaster()
on the BufferedImage
. This will give you a Raster
object, which has methods to access the pixel data (it has several getPixel()
/ getPixels()
methods).
Lookup the API documentation for javax.imageio.ImageIO
, java.awt.image.BufferedImage
, java.awt.image.Raster
etc.
ImageIO supports a number of image formats by default: JPEG, PNG, BMP, WBMP and GIF. It's possible to add support for more formats (you'd need a plug-in that implements the ImageIO service provider interface).
See also the following tutorial: Working with Images
Answer by Aturio for Convert InputStream to byte array in Java
Input Stream is ... ByteArrayOutputStream bos = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { bos.write(next); next = in.read(); } bos.flush(); byte[] result = bos.toByteArray();
Answer by Madhu for Convert InputStream to byte array in Java
/*InputStream class_InputStream = null; I am reading class from DB class_InputStream = rs.getBinaryStream(1); Your Input stream could be from any source */ int thisLine; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((thisLine = class_InputStream.read()) != -1) { bos.write(thisLine); } bos.flush(); byte [] yourBytes = bos.toByteArray(); /*Don't forget in the finally block to close ByteArrayOutputStream & InputStream In my case the IS is from resultset so just closing the rs will do it*/ if (bos != null){ bos.close(); }
Answer by pihentagy for Convert InputStream to byte array in Java
@Adamski: You can avoid buffer entirely.
Code copied from http://www.exampledepot.com/egs/java.io/File2ByteArray.html (Yes, it is very verbose, but needs half the size of memory as the other solution.)
// Returns the contents of the file in a byte array. public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int)length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } // Close the input stream and return bytes is.close(); return bytes; }
Answer by dermoritz for Convert InputStream to byte array in Java
i don't know why this is found so difficult (some pages to scroll in google). so i write my favorite answer here on page number one if googled for "java inputstream to bytearray":
Use Vanilla Javas "DataInputStream" and its "readFully" Method (exists at least since Java 1.4):
... byte[] imgDataBa = new byte[(int)imgFile.length()]; DataInputStream dataIs = new DataInputStream(new FileInputStream(imgFile)); dataIs.readFully(imgDataBa); ...
there are some other flavors of this method, but this i used all the time for this use case
Answer by akostadinov for Convert InputStream to byte array in Java
I tried to edit @numan's answer with a fix for writing garbage data but edit was rejected. While this short piece of code is nothing brilliant I can't see any other better answer. Here's what makes most sense to me:
ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; // you can configure the buffer size int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams in.close(); // call this in a finally block byte[] result = out.toByteArray();
btw ByteArrayOutputStream need not be closed. try/finally constructs omitted for readability
Answer by oliverkn for Convert InputStream to byte array in Java
public static byte[] getBytesFromInputStream(InputStream is) throws IOException { try (ByteArrayOutputStream os = new ByteArrayOutputStream();) { byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1;) os.write(buffer, 0, len); os.flush(); return os.toByteArray(); } }
Answer by YulCheney for Convert InputStream to byte array in Java
ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (true) { int r = in.read(buffer); if (r == -1) break; out.write(buffer, 0, r); } byte[] ret = out.toByteArray();
Answer by bertie for Convert InputStream to byte array in Java
If you happen to use google guava, it'll be as simple as :
byte[] bytes = ByteStreams.toByteArray(inputStream);
Answer by Kristian Kraljic for Convert InputStream to byte array in Java
If you don't want to use the Apache commons-io library, this snippet is taken from the sun.misc.IOUtils class. It's nearly twice as fast as the common implementation using ByteBuffers:
public static byte[] readFully(InputStream is, int length, boolean readAll) throws IOException { byte[] output = {}; if (length == -1) length = Integer.MAX_VALUE; int pos = 0; while (pos < length) { int bytesToRead; if (pos >= output.length) { // Only expand when there's no room bytesToRead = Math.min(length - pos, output.length + 1024); if (output.length < pos + bytesToRead) { output = Arrays.copyOf(output, pos + bytesToRead); } } else { bytesToRead = output.length - pos; } int cc = is.read(output, pos, bytesToRead); if (cc < 0) { if (readAll && length != Integer.MAX_VALUE) { throw new EOFException("Detect premature EOF"); } else { if (output.length != pos) { output = Arrays.copyOf(output, pos); } break; } } pos += cc; } return output; }
Answer by Christian d'Heureuse for Convert InputStream to byte array in Java
Here is an optimized version, that tries to avoid copying data bytes as much as possible:
private static byte[] loadStream (InputStream stream) throws IOException { int available = stream.available(); int expectedSize = available > 0 ? available : -1; return loadStream(stream, expectedSize); } private static byte[] loadStream (InputStream stream, int expectedSize) throws IOException { int basicBufferSize = 0x4000; int initialBufferSize = (expectedSize >= 0) ? expectedSize : basicBufferSize; byte[] buf = new byte[initialBufferSize]; int pos = 0; while (true) { if (pos == buf.length) { int readAhead = -1; if (pos == expectedSize) { readAhead = stream.read(); // test whether EOF is at expectedSize if (readAhead == -1) { return buf; }} int newBufferSize = Math.max(2 * buf.length, basicBufferSize); buf = Arrays.copyOf(buf, newBufferSize); if (readAhead != -1) { buf[pos++] = (byte)readAhead; }} int len = stream.read(buf, pos, buf.length - pos); if (len < 0) { return Arrays.copyOf(buf, pos); } pos += len; }}
Answer by Simple-Solution for Convert InputStream to byte array in Java
I know it's too late but here I think is cleaner solution that's more readable...
/** * method converts {@link InputStream} Object into byte[] array. * * @param stream the {@link InputStream} Object. * @return the byte[] array representation of received {@link InputStream} Object. * @throws IOException if an error occurs. */ public static byte[] streamToByteArray(InputStream stream) throws IOException { byte[] buffer = new byte[1024]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int line = 0; // read bytes from stream, and store them in buffer while ((line = stream.read(buffer)) != -1) { // Writes bytes from byte array (buffer) into output stream. os.write(buffer, 0, line); } stream.close(); os.flush(); os.close(); return os.toByteArray(); }
Answer by Huy Tower for Convert InputStream to byte array in Java
The other case to get correct byte array via stream, after send request to server and waiting for the response.
/** * Begin setup TCP connection to PC app * to open integrate connection between mobile app and pc app (or mobile app) */ mSocket = new Socket(IP, port); // mSocket.setSoTimeout(30000); DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream()); String str = "MobileRequest#" + params[0] + "#"; mDos.write(str.getBytes()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } /* Since data are accepted as byte, all of them will be collected in the following byte array which initialised with accepted data length. */ DataInputStream mDis = new DataInputStream(mSocket.getInputStream()); byte[] data = new byte[mDis.available()]; // Collecting data into byte array for (int i = 0; i < data.length; i++) data[i] = mDis.readByte(); // Converting collected data in byte array into String. String RESPONSE = new String(data);
Answer by Luke Hutchison for Convert InputStream to byte array in Java
You're doing an extra copy if you use ByteArrayOutputStream. If you know the length of the stream before you start reading it (e.g. the InputStream is actually a FileInputStream, and you can call file.length() on the file, or the InputStream is a zipfile entry InputStream, and you can call zipEntry.length()), then it's far better to write directly into the byte[] array -- it uses half the memory, and saves time.
// Read the file contents into a byte[] array byte[] buf = new byte[inputStreamLength]; int bytesRead = Math.max(0, inputStream.read(buf)); // If needed: for safety, truncate the array if the file may somehow get // truncated during the read operation byte[] contents = bytesRead == inputStreamLength ? buf : Arrays.copyOf(buf, bytesRead);
N.B. the last line above deals with files getting truncated while the stream is being read, if you need to handle that possibility, but if the file gets longer while the stream is being read, the contents in the byte[] array will not be lengthened to include the new file content, the array will simply be truncated to the old length inputStreamLength.
Answer by thusharaK for Convert InputStream to byte array in Java
This works for me,
if(inputStream != null){ ByteArrayOutputStream contentStream = readSourceContent(inputStream); String stringContent = contentStream.toString(); byte[] byteArr = encodeString(stringContent); }
readSourceContent()
public static ByteArrayOutputStream readSourceContent(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int nextChar; try { while ((nextChar = inputStream.read()) != -1) { outputStream.write(nextChar); } outputStream.flush(); } catch (IOException e) { throw new IOException("Exception occurred while reading content", e); } return outputStream; }
encodeString()
public static byte[] encodeString(String content) throws UnsupportedEncodingException { byte[] bytes; try { bytes = content.getBytes(); } catch (UnsupportedEncodingException e) { String msg = ENCODING + " is unsupported encoding type"; log.error(msg,e); throw new UnsupportedEncodingException(msg, e); } return bytes; }
Answer by yichouangle for Convert InputStream to byte array in Java
See the InputStream.available()
documentation:
It is particularly important to realize that you must not use this method to size a container and assume that you can read the entirety of the stream without needing to resize the container. Such callers should probably write everything they read to a ByteArrayOutputStream and convert that to a byte array. Alternatively, if you're reading from a file, File.length returns the current length of the file (though assuming the file's length can't change may be incorrect, reading a file is inherently racy).
Answer by cchcc for Convert InputStream to byte array in Java
I use this.
public static byte[] toByteArray(InputStream is) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { byte[] b = new byte[4096]; int n = 0; while ((n = is.read(b)) != -1) { output.write(b, 0, n); } return output.toByteArray(); } finally { output.close(); } }
0 comments:
Post a Comment