• 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.
[pastacode lang=”java” manual=”import%20java.io.BufferedReader%3B%0Aimport%20java.io.ByteArrayInputStream%3B%0Aimport%20java.io.IOException%3B%0Aimport%20java.io.InputStream%3B%0Aimport%20java.io.InputStreamReader%3B%0A” message=”java code” highlight=”” provider=”manual”/] [pastacode lang=”java” manual=”public%20class%20WikitechyExample%20%0A%7B%0A%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20throws%20IOException%20%0A%7B%0A%20%20%20%20%20%20%20InputStreamReader%20isr%20%3D%20null%3B%0A%20%20%20%20%20%20%20BufferedReader%20br%20%3D%20null%3B%0A%20%20%20%20%20%20%20InputStream%20is%20%3D%20new%20ByteArrayInputStream(%22Welcome%20to%20wikitechy%22.getBytes())%3B%0AStringBuilder%20sb%20%3D%20new%20StringBuilder()%3B%0A%20%20%20%20%20%20%20String%20content%3B%0A%20try%20%0A%7B%0A%20%20%20%20%20%20%20%20%20%20%20isr%20%3D%20new%20InputStreamReader(is)%3B%0A%09%20%20%20br%20%3D%20new%20BufferedReader(isr)%3B%0A%09%20%20%20while%20((content%20%3D%20br.readLine())%20!%3D%20null)%20%0A%7B%0A%09%09sb.append(content)%3B%0A%7D%0A%7D%20catch%20(IOException%20ioe)%20%0A%7B%0A%09%09System.out.println(%22IO%20Exception%20occurred%22)%3B%0A%09%09ioe.printStackTrace()%3B%09%0A%20%7D%20finally%20%0A%7B%0A%09%09isr.close()%3B%0A%09%09br.close()%3B%0A%7D%0A%20%20%20%20%20%20%20%20String%20mystring%20%3D%20sb.toString()%3B%0A%09System.out.println(mystring)%3B%0A%20%7D%0A%7D%0A” message=”java code” highlight=”” provider=”manual”/] [ad type=”banner”]

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

[pastacode lang=”java” manual=”package%20com.howtodoinjava.demo.io%3B%0A%20import%20java.io.BufferedReader%3B%0Aimport%20java.io.File%3B%0Aimport%20java.io.FileInputStream%3B%0Aimport%20java.io.FileNotFoundException%3B%0Aimport%20java.io.IOException%3B%0Aimport%20java.io.InputStream%3B%0Aimport%20java.io.InputStreamReader%3B%0A%20public%20class%20ReadStreamIntoStringUsingReader%7B%0A%20%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20throws%20FileNotFoundException%2C%20IOException%20%20%7B%0A%20%20%20%20%20%20%20%20InputStream%20wikiin%20%3D%20new%20FileInputStream(new%20File(%22C%3A%2Ftemp%2Ftest.txt%22))%3B%0A%20%20%20%20%20%20%20%20BufferedReader%20reader%20%3D%20new%20BufferedReader(new%20InputStreamReader(wikiin))%3B%0A%20%20%20%20%20%20%20%20StringBuilder%20out%20%3D%20new%20StringBuilder()%3B%0A%20%20%20%20%20%20%20%20String%20line%3B%0A%20%20%20%20%20%20%20%20while%20((line%20%3D%20reader.readLine())%20!%3D%20null)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20out.append(line)%3B%0A%7D%0A%20%20%20%20%20%20%20%20System.out.println(out.toString())%3B%20%20%20%2F%2FPrints%20the%20string%20content%20read%20from%20input%20stream%0A%20%20%20%20%20%20%20%20reader.close()%3B%0A%7D%0A%7D%0A” message=”java code” highlight=”” provider=”manual”/]

Using apache commons IOUtils

  • Apache commons has a very classy facility for this purpose which makes code is easy to read.
[pastacode lang=”java” manual=”package%20com.howtodoinjava.demo.io%3B%0Aimport%20java.io.File%3B%0Aimport%20java.io.FileInputStream%3B%0Aimport%20java.io.FileNotFoundException%3B%0Aimport%20java.io.IOException%3B%0Aimport%20java.io.StringWriter%3B%0Aimport%20org.apache.commons.io.IOUtils%3B%0A%20public%20class%20ReadStreamIntoStringUsingIOUtils%0A%7B%0A%20public%20static%20void%20main(String%5B%5D%20args)%20throws%20FileNotFoundException%2C%20IOException%20%7B%0A%20%20%20%20%20%20%20%20%2F%2FMethod%201%20IOUtils.copy()%0A%20%20%20%20%20%20%20%20StringWriter%20writer%20%3D%20new%20StringWriter()%3B%0A%20%20%20%20%20%20%20%20IOUtils.copy(new%20FileInputStream(new%20File(%22C%3A%2Ftemp%2Ftest.txt%22))%2C%20writer%2C%20%22UTF-8%22)%3B%0A%20%20%20%20%20%20%20%20String%20theString%20%3D%20writer.toString()%3B%0A%20%20%20%20%20%20%20%20System.out.println(theString)%3B%0A%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%2F%2FMethod%202%20IOUtils.toString()%0A%20%20%20%20%20%20%20%20String%20theString2%20%3D%20IOUtils.toString(new%20FileInputStream(new%20File(%22C%3A%2Ftemp%2Ftest.txt%22))%2C%20%22UTF-8%22)%3B%0A%20%20%20%20%20%20%20%20System.out.println(theString2)%3B%0A%20%20%20%20%7D%7D%0A” message=”java code” highlight=”” provider=”manual”/] [ad type=”banner”]

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.
[pastacode lang=”java” manual=”package%20com.howtodoinjava.demo.io%3B%0Aimport%20java.io.File%3B%0Aimport%20java.io.FileInputStream%3B%0Aimport%20java.io.FileNotFoundException%3B%0Aimport%20java.io.IOException%3B%0Apublic%20class%20ReadStreamIntoStringUsingScanner%0A%7B%0A%20%20%20%20%40SuppressWarnings(%22resource%22)%0A%20%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20throws%20FileNotFoundException%2C%20IOException%20%0A%7B%0A%20%20%20%20%20%20%20%20FileInputStream%20fin%20%3D%20new%20FileInputStream(new%20File(%22C%3A%2Ftemp%2Ftest.txt%22))%3B%0A%20%20%20%20%20%20%20%20java.util.Scanner%20scanner%20%3D%20new%20java.util.Scanner(fin%2C%22UTF-8%22).useDelimiter(%22%5CA%22)%3B%0A%20%20%20%20%20%20%20%20String%20theString%20%3D%20scanner.hasNext()%20%3F%20scanner.next()%20%3A%20%22%22%3B%0A%20%20%20%20%20%20%20%20System.out.println(theString)%3B%0A%20%20%20%20%20%20%20%20scanner.close()%3B%0A%7D%0A%7D%0A” message=”java code” highlight=”” provider=”manual”/]

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

[pastacode lang=”java” manual=”try%C2%A0(InputStream%C2%A0in%C2%A0%3D%C2%A0new%C2%A0FileInputStream(%22wikitechy.txt%22)%3B%0A%C2%A0BufferedReader%C2%A0r%C2%A0%3D%C2%A0new%C2%A0BufferedReader(new%C2%A0InputStreamReader(in%2C%C2%A0StandardCharsets.UTF_8)))%0A%20%7B%C2%A0%0AString%C2%A0str%C2%A0%3D%C2%A0null%3B%C2%A0%0AStringBuilder%C2%A0sb%C2%A0%3D%C2%A0new%C2%A0StringBuilder(8192)%3B%C2%A0%0Awhile%C2%A0((str%C2%A0%3D%C2%A0r.readLine())%C2%A0!%3D%C2%A0null)%20%0A%7B%0A%20sb.append(str)%3B%20%0A%7D%C2%A0%0ASystem.out.println(%22data%20from%20InputStream%20as%20String%20%3A%20%22%C2%A0%2B%C2%A0sb.toString())%3B%20%0A%7D%0A%C2%A0catch%C2%A0(IOException%C2%A0ioe)%20%0A%7B%20%0Aioe.printStackTrace()%3B%20%0A%7D” message=”java code” highlight=”” provider=”manual”/]
  • 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.
[pastacode lang=”java” manual=”try%C2%A0(FileInputStream%C2%A0fis%C2%A0%3D%C2%A0new%C2%A0FileInputStream(%22wikitechy.txt%22)%3B)%20%0A%7B%C2%A0%0AString%C2%A0text%C2%A0%3D%C2%A0IOUtils.toString(fis%2C%C2%A0StandardCharsets.UTF_8.name())%3B%C2%A0%0ASystem.out.println(%22String%20generated%20by%20reading%20InputStream%20in%20Java%20%3A%20%22%C2%A0%2B%C2%A0text)%3B%20%0A%7D%C2%A0%0Acatch%C2%A0(IOException%C2%A0io)%20%0A%7B%20%0Aio.printStackTrace()%3B%0A%20%7D” message=”java code” highlight=”” provider=”manual”/] [ad type=”banner”]

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.
[pastacode lang=”java” manual=”String%C2%A0stringWithSpecialChar%C2%A0%3D%C2%A0%22Soci%C3%A9t%C3%A9%20G%C3%A9n%C3%A9rale%22%3B%0A%C2%A0try%C2%A0(final%C2%A0InputStream%C2%A0in%C2%A0%3D%C2%A0new%C2%A0ByteArrayInputStream(stringWithSpecialChar.getBytes(%22UTF-8%22))%3B%0A%C2%A0final%C2%A0InputStreamReader%C2%A0inr%C2%A0%3D%C2%A0new%C2%A0InputStreamReader(in))%20%0A%7B%0A%C2%A0String%C2%A0text%C2%A0%3D%C2%A0CharStreams.toString(inr)%3B%C2%A0System.out.println(%22String%20from%20InputStream%20in%20Java%3A%20%22%C2%A0%2B%C2%A0text)%3B%20%0A%7D%C2%A0%0Acatch%C2%A0(IOException%C2%A0e)%0A%20%7B%0A%20e.printStackTrace()%3B%0A%20%7D” message=”java code” highlight=”” provider=”manual”/]

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.

[pastacode lang=”java” manual=”import%C2%A0java.io.BufferedReader%3B%C2%A0%0Aimport%C2%A0java.io.ByteArrayInputStream%3B%C2%A0%0Aimport%C2%A0java.io.FileInputStream%3B%C2%A0%0Aimport%C2%A0java.io.FileNotFoundException%3B%C2%A0%0Aimport%C2%A0java.io.IOException%3B%0A%C2%A0import%C2%A0java.io.InputStream%3B%C2%A0%0Aimport%C2%A0java.io.InputStreamReader%3B%C2%A0%0Aimport%C2%A0java.nio.charset.StandardCharsets%3B%0A%C2%A0import%C2%A0org.apache.commons.io.Charsets%3B%C2%A0%0Aimport%C2%A0org.apache.commons.io.IOUtils%3B%0A%C2%A0importcom.google.common.io.CharStreams%3B%0A%C2%A0import%C2%A0com.google.common.io.InputSupplier%0Apublic%C2%A0class%C2%A0InputStreamToString%C2%A0%7B%C2%A0public%C2%A0static%C2%A0void%C2%A0main(String%C2%A0args%5B%5D)%0A%20%7B%0A%C2%A0%2F%2F%20InputStream%20to%20String%20-%20Core%20Java%20Example%C2%A0%0Atry%C2%A0(InputStream%C2%A0in%C2%A0%3D%C2%A0new%C2%A0FileInputStream(%22wikitechy.txt%22)%3B%C2%A0%0ABufferedReader%C2%A0r%C2%A0%3D%C2%A0new%C2%A0BufferedReader(new%C2%A0InputStreamReader(in%2C%C2%A0StandardCharsets.UTF_8)))%20%0A%7B%C2%A0%0AString%C2%A0str%C2%A0%3D%C2%A0null%3B%C2%A0%0AStringBuilder%C2%A0sb%C2%A0%3D%C2%A0new%C2%A0StringBuilder(8192)%3B%C2%A0%0Awhile%C2%A0((str%C2%A0%3D%C2%A0r.readLine())%C2%A0!%3D%C2%A0null)%20%0A%7B%20%0Asb.append(str)%3B%20%0A%7D%C2%A0%0ASystem.out.println(%22data%20from%20InputStream%20as%20String%20%3A%20%22%C2%A0%2B%C2%A0sb.toString())%3B%20%0A%7D%C2%A0%0Acatch%C2%A0(IOException%C2%A0ioe)%20%0A%7B%20%0Aioe.printStackTrace()%3B%0A%7D” message=”java code” highlight=”” provider=”manual”/] [pastacode lang=”java” manual=”%2F%2F%20Converting%20InputStream%20to%20String%20in%20Java%20-%20Google%20Guava%20Example%C2%A0%0AString%C2%A0stringWithSpecialChar%C2%A0%3D%C2%A0%22Soci%C3%A9t%C3%A9G%C3%A9n%C3%A9rale%22%3B%C2%A0%0Atry%C2%A0(final%C2%A0InputStream%C2%A0in%C2%A0%3D%C2%A0new%C2%A0ByteArrayInputStream(stringWithSpecialChar.getBytes(%22UTF-8%22))%3B%C2%A0%0Afinal%C2%A0InputStreamReader%C2%A0inr%C2%A0%3D%C2%A0new%C2%A0InputStreamReader(in))%20%0A%7B%C2%A0%0AString%C2%A0text%C2%A0%3D%C2%A0CharStreams.toString(inr)%3B%C2%A0%0ASystem.out.println(%22String%20from%20InputStream%20in%20Java%3A%20%22%C2%A0%2Btext)%3B%0A%20%7D%C2%A0%0Acatch%C2%A0(IOException%C2%A0e)%20%7B%20e.printStackTrace()%3B%20%0A%7D%C2%A0″ message=”java code” highlight=”” provider=”manual”/] [pastacode lang=”java” manual=”%2F%2F%20Reading%20data%20from%20InputStream%20as%20String%20in%20Java%20-%20Apache%20Commons%20Example%C2%A0%0Atry%C2%A0(FileInputStream%C2%A0fis%C2%A0%3D%C2%A0new%C2%A0FileInputStream(%22wikitechy.txt%22)%3B)%0A%20%7B%C2%A0%0AString%C2%A0text%C2%A0%3D%C2%A0IOUtils.toString(fis%2C%C2%A0StandardCharsets.UTF_8.name())%3B%C2%A0%0ASystem.out.println(%22String%20generated%20by%20reading%20InputStream%20in%20Java%20%3A%20%22%C2%A0%2B%C2%A0text)%3B%0A%20%7D%C2%A0%0Acatch%C2%A0(IOException%C2%A0io)%20%0A%7B%20%0Aio.printStackTrace()%3B%20%0A%7D%20%0A%7D%0A%20%7D” message=”java code” highlight=”” provider=”manual”/]

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”]

Categorized in: