• 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.
java code
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
java code
public class WikitechyExample 
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr = null;
BufferedReader br = null;
InputStream is = new ByteArrayInputStream("Welcome to wikitechy".getBytes());
StringBuilder sb = new StringBuilder();
String content;
try
{
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((content = br.readLine()) != null)
{
sb.append(content);
}
} catch (IOException ioe)
{
System.out.println("IO Exception occurred");
ioe.printStackTrace();
} finally
{
isr.close();
br.close();
}
String mystring = sb.toString();
System.out.println(mystring);
}
}
[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

java code
package com.howtodoinjava.demo.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadStreamIntoStringUsingReader{
public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream wikiin = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(wikiin));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();
}
}

Using apache commons IOUtils

  • Apache commons has a very classy facility for this purpose which makes code is easy to read.
java code
package com.howtodoinjava.demo.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import org.apache.commons.io.IOUtils;
public class ReadStreamIntoStringUsingIOUtils
{
public static void main(String[] args) throws FileNotFoundException, IOException {
//Method 1 IOUtils.copy()
StringWriter writer = new StringWriter();
IOUtils.copy(new FileInputStream(new File("C:/temp/test.txt")), writer, "UTF-8");
String theString = writer.toString();
System.out.println(theString);

//Method 2 IOUtils.toString()
String theString2 = IOUtils.toString(new FileInputStream(new File("C:/temp/test.txt")), "UTF-8");
System.out.println(theString2);
}}
[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.
java code
package com.howtodoinjava.demo.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadStreamIntoStringUsingScanner
{
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException, IOException
{
FileInputStream fin = new FileInputStream(new File("C:/temp/test.txt"));
java.util.Scanner scanner = new java.util.Scanner(fin,"UTF-8").useDelimiter("\A");
String theString = scanner.hasNext() ? scanner.next() : "";
System.out.println(theString);
scanner.close();
}
}

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

java code
try (InputStream in = new FileInputStream("wikitechy.txt");
 BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)))

String str = null; 
StringBuilder sb = new StringBuilder(8192); 
while ((str = r.readLine()) != null)
{
sb.append(str);

System.out.println("data from InputStream as String : " + sb.toString());
}
 catch (IOException ioe)
{
ioe.printStackTrace();
}
  • 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.
java code
try (FileInputStream fis = new FileInputStream("wikitechy.txt");) 

String text = IOUtils.toString(fis, StandardCharsets.UTF_8.name()); 
System.out.println("String generated by reading InputStream in Java : " + text);

catch (IOException io)
{
io.printStackTrace();
}
[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.
java code
String stringWithSpecialChar = "Société Générale";
 try (final InputStream in = new ByteArrayInputStream(stringWithSpecialChar.getBytes("UTF-8"));
 final InputStreamReader inr = new InputStreamReader(in))
{
 String text = CharStreams.toString(inr); System.out.println("String from InputStream in Java: " + text);

catch (IOException e)
{
e.printStackTrace();
}

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.

java code
import java.io.BufferedReader; 
import java.io.ByteArrayInputStream; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException;
 import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.nio.charset.StandardCharsets;
 import org.apache.commons.io.Charsets; 
import org.apache.commons.io.IOUtils;
 importcom.google.common.io.CharStreams;
 import com.google.common.io.InputSupplier
public class InputStreamToString { public static void main(String args[])
{
 // InputStream to String - Core Java Example 
try (InputStream in = new FileInputStream("wikitechy.txt"); 
BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)))

String str = null; 
StringBuilder sb = new StringBuilder(8192); 
while ((str = r.readLine()) != null)
{
sb.append(str);

System.out.println("data from InputStream as String : " + sb.toString());

catch (IOException ioe)
{
ioe.printStackTrace();
}
java code
// Converting InputStream to String in Java - Google Guava Example 
String stringWithSpecialChar = "SociétéGénérale"; 
try (final InputStream in = new ByteArrayInputStream(stringWithSpecialChar.getBytes("UTF-8")); 
final InputStreamReader inr = new InputStreamReader(in))

String text = CharStreams.toString(inr); 
System.out.println("String from InputStream in Java: " +text);

catch (IOException e) { e.printStackTrace();
java code
// Reading data from InputStream as String in Java - Apache Commons Example 
try (FileInputStream fis = new FileInputStream("wikitechy.txt");)

String text = IOUtils.toString(fis, StandardCharsets.UTF_8.name()); 
System.out.println("String generated by reading InputStream in Java : " + text);

catch (IOException io)
{
io.printStackTrace();
}
}
}

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: