
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
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
- Related Questions & Answers
- How to convert byte array to an object stream in C#?
- How to convert an object to byte array in java?
- Program to convert Stream to an Array in Java
- How to Convert a Java 8 Stream to an Array?
- How to convert/read an input stream into a string in java?
- How to convert BLOB to Byte Array in java?
- How to convert Byte Array to BLOB in java?
- How to convert Byte Array to Image in java?
- How to convert Image to Byte Array in java?
- How to convert InputStream to byte array in Java?
- Character Stream vs Byte Stream in Java
- Convert an Iterator to Stream in Java
- Convert an Iterable to Stream in Java
- Java Program to create Stream from a String/Byte Array
- How to convert a PDF to byte array in Java?
Advertisements