- The Java.io.InputStream class is the superclass of all classes representing an input stream of bytes.
- Applications that need to define a subclass of InputStream must always provide a method that returns the next byte of input
- It explains concept of how to read and write date e.g. bytes from input source like file, network, keyboard and writing data to console, file, network and program.
- InputStream is used to read data and OutputStream is used to write data.
- Data can be on any format (e.g. Text or Binary). We can even read data in particular type by using DataInputStream.
- Java provides char, int, float, double, long and other data types to store data read in that way.
- Character streams (e.g. Readers) are used to read character data while Byte Streams (e.g. InputStream) are used to read binary data.
Example: Read and Convert an InputStream to a String
Here is the complete example of how to read and convert an InputStream to a String.
The steps involved are:
- We have initialized the Input Stream after converting the file content to bytes using get Bytes() method and then using the Byte Array Input Stream which contains an internal buffer that contains bytes that may be read from the stream.
- Read the Input Stream using Input Stream Reader.
- Read Input Stream Reader using Buffered Reader.
- Appended each line to a String Builder object which has been read by Buffered Reader.
- Finally converted the String Builder to String using to String() method.
Output:
Welcome to wikitechy
3 Ways to Read files in java NIO:
- If we are using java.nio package for reading a file, we can read some effective ways to read files in java NIO.
- Using BufferedReader
- Using apache commons IOUtils
- Using java.util.Scanner
Using BufferedReader
Using apache commons IOUtils
- Apache commons has a very classy facility for this purpose which makes code is easy to read.
Using java.util.Scanner
- The reason it works is because Scanner iterates over tokens in the stream, and in this case we separate tokens using “beginning of the input boundary” (A) thus giving us only one token for the entire contents of the stream.
Read InputStream as String in Java – JDK7, Guava and Apache Commons
- Inside Java program, we often use String object to store and pass file data, that’s why we need a way to convert InputStream to String in Java.
- For example In Java, we read data from file or socket using InputStream and write data using OutputStream.
- Java programming language provides streams to read data from a file, a socket and from other sources e.g. byte array, but developers often find themselves with several issues e.g. how to open connection to read data, how to close connection after reading or writing into file, how to handle IOException (e.g. FileNotFoundException, EOFFileException etc).
3 Example to Read InputStream as String in java:
- Using Core Java classes
- Using Apache Commons IO
- Using Google Guava library
Using Core Java classes
- This approach is best suited to application running on Java 7, as we are using try-with-resource statements to automatically close input streams, but we can just take out that piece and can close streams in finally block, if we are running on Java 6 or lower version.
- Here is the steps and code sample of reading InputStream as String in Java :
Step 1: Open FileInputStream to read contents of File as InputStream.
Step 2: Create InputStreamReader with character encoding to read byte as characters
Step 3: Create BufferedReader to read file data line by line
Step 4: Use StringBuilder to combine lines
- Closing of InputStream is taken care by Java itself because they are declared as try-with-resource statement.
- Our File contains a single line, which contains some French characters, to demonstrate use of character encoding.
- We have provided UTF-8 to InputStreamReader just for this purpose.
Using Apache Commons IO
- In this example, we are using IOUtils class from Apache commons IO to read InputStream data as String.
- It provides a toString() method to convert InputStream to String.
- This is the most easiest way to get String from stream, but we should also don’t rely on them to close our streams.
- If we are using automatic resource management feature of Java 7, which closes any resource opened in try() statement.
Using Google Guava library
- In this example, we have used Google Guava library to read contents of InputStream as String.
- Here input stream is not obtained from file instead from a byte array, which is generated by converting an String to byte array.
- It always better to provide encoding while calling getBytes() method of String, so that data is converted correctly.
- In example, we have provided “UTF-8”, though we can also use StandardCharsets.UTF_8.name().
- CharStreams.toString() doesn’t close Stream from which it is reading characters, that’s why we have opened stream in try (…) parenthesis, so that it will be automatically closed by Java.
Complete java program of inputstream to string in java
- Here is the full code listing of 3 ways to read InputStream as String in Java Program.
- In order to run this program, copy this code into a file and save it as InputStreamToString.java, after this compile this file using javac command, if javac is not in our included in our PATH environment variable, then we can directly run it from bin folder of our JDK installation directory, also known as JAVA_HOME.
- After compilation, we can run our program by using java command e.g. java -classpath . InputStreamToString .
It shows examples from core Java, Google Guava and Apache commons library.
Output:
data from InputStream as String : Société Générale is a French bank Headquarters at Île-de-France, France
String from InputStream in Java: Société Générale
String generated by reading InputStream in Java : Société Générale is a French bank Headquarters at Île-de-France, France
[ad type=”banner”]