![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Advertisements