InputStream to String Conversion Example
Converting InputStream to String inwards Java has dice rattling slow after introduction of Scanner cast inwards Java five together with due to evolution of several opened upward rootage libraries similar Apache common IOUtils together with Google Open rootage guava-libraries which provides splendid back upward to convert InputStream to String inwards Java program. nosotros often require to convert InputStream to String while working inwards Java for representative if yous are reading XML files from InputStream together with after performing XSLT transformation on it or if InputStream is reading information from text file or text input Source together with nosotros either desire to log Strings inwards log file or desire to operate on whole String. Before Java five yous would possess got to write lots of boiler plate code to read String trouble yesteryear line or byte yesteryear byte depending upon whether yous are using either BufferedReader or non but every bit I said since JDK five added Scanner for reading input, its fairly slow to convert InputStream into String.
Before Converting whatever InputStream or ByteStream into String don't forget to furnish character encoding or charSet which tells Java Which characters to facial expression from those streams of bytes. inwards the absence of right graphic symbol encoding yous mightiness alter the output because same bytes tin live used to stand upward for dissimilar graphic symbol inwards dissimilar encoding. Another matter to dice along inwards heed is that if yous don't furnish graphic symbol encoding, Default graphic symbol encoding inwards Java volition live used which tin live specified from System holding "file.encoding" or "UTF-8" if file.encoding is non specified. In this Java tutorial nosotros volition come across five dissimilar representative of converting InputStream to String inwards Java both yesteryear using measure JDK libraries together with using opened upward rootage libraries.
How to convert InputStream to String inwards Java – five Examples
here are dissimilar ways to convert InputStream to String inwards Java, maiden off nosotros volition come across close elementary agency of reading InputStream every bit String.
InputStream to String - Using Java five Scanner
constructor which possess got an InputStream, a graphic symbol encoding together with a delimiter to read String from InputStream. Here nosotros possess got used delimiter every bit "\A" which is boundary jibe for kickoff of the input every bit declared inwards java.util.regex.Pattern together with that's why Scanner is returning whole String cast InputStream. I oftentimes utilization this technique to read input from user inwards Java using System.in which is close mutual representative of InputStream inwards Java, but every bit demonstrated hither this tin likewise live used to read text file inwards Java.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Java programme representative to demonstrate How to convert InputStream into String yesteryear using JDK
* Scanner utility. This programme volition piece of job Java five onwards every bit Scanner was added inwards Java 5.
*/
public class InputStreamTest {
public static void main(String args[]) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
System.out.println(inputStreamString);
}
}
Output:
This String is read from InputStream yesteryear changing InputStream to String inwards Java.
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Java programme representative to demonstrate How to convert InputStream into String yesteryear using JDK
* Scanner utility. This programme volition piece of job Java five onwards every bit Scanner was added inwards Java 5.
*/
public class InputStreamTest {
public static void main(String args[]) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
System.out.println(inputStreamString);
}
}
Output:
This String is read from InputStream yesteryear changing InputStream to String inwards Java.
If yous desire to come across how an wrong graphic symbol encoding completely changes the String only modify the graphic symbol encoding cast "UTF-8" to "UTF-16" together with yous come across Chinese(may be) characters instead of English.
Output:
?????????????!???????????!??????^(4)????????
?????????????!???????????!??????^(4)????????
Convert InputStream to String - Plain erstwhile JDK4 Example
If yous yet require to do it on plainly erstwhile Java on JDK4 without including whatever additional dependency inwards your PATH together with Classpath than hither is quick representative using BufferedReader in Java, Remember yous tin likewise do this yesteryear reading byte yesteryear byte from InputStream but that's rattling wearisome together with thus visit using BufferedReader for ameliorate functioning fifty-fifty if yous code on JDK4 . For to a greater extent than functioning tips come across my post service 4 JDBC functioning tips inwards Java program. Let’s come across representative of converting InputStream to String using BufferedReader inwards Java.
/**
* Java programme to demonstrate How to read InputStream every bit String
* Java programme to demonstrate How to read InputStream every bit String
* using BufferedReader together with StringBuilder inwards Java.
* This is erstwhile together with measure agency of converting an InputStream into String inwards Java
*/
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String trouble = bufferedReader.readLine();
while(line != null){
inputStringBuilder.append(line);inputStringBuilder.append('\n');
trouble = bufferedReader.readLine();
}
System.out.println(inputStringBuilder.toString());
}
Output:
This String is read from InputStream yesteryear changing InputStream to String inwards Java.
second line
* This is erstwhile together with measure agency of converting an InputStream into String inwards Java
*/
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String trouble = bufferedReader.readLine();
while(line != null){
inputStringBuilder.append(line);inputStringBuilder.append('\n');
trouble = bufferedReader.readLine();
}
System.out.println(inputStringBuilder.toString());
}
Output:
This String is read from InputStream yesteryear changing InputStream to String inwards Java.
second line
This is practiced plainly erstwhile Java method of converting InputStream to String without adding whatever extra dependency but recollect its converting \r to \n because nosotros are reading trouble yesteryear line, which inwards close cases fine.
Read InputStream to String - Using Apache IOUtils library
As I said before at that topographic point are many opened upward rootage library inwards Java which makes coding lot to a greater extent than easier than whatever other language. Here is code representative for How to convert InputStream to String inwards Java using Apache IOUtils
/**
* Example of How to read InputStream into String yesteryear using Apache IOUtils library.
* Nice together with laid clean agency of getting InputStream every bit String inwards Java
*/
FileInputStream fis = new FileInputStream("c:/sample.txt");
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);
* Example of How to read InputStream into String yesteryear using Apache IOUtils library.
* Nice together with laid clean agency of getting InputStream every bit String inwards Java
*/
FileInputStream fis = new FileInputStream("c:/sample.txt");
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);
Isn't it a compact agency of converting InputStream to String inwards Java, only i trouble of code together with that does convey assist of graphic symbol encoding every bit well..
InputStream to String - Using Google's guava-libraries
Google has opened upward rootage its ain laid of Java libraries they utilization for Java development within Google. it has lots of utility percentage together with likewise complements Apache common package. Here is a quick agency of converting InputStream to String using Google libraries:
String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
Regarding dependency, You require to include guava library i.e. guava-11.0.1.jar inwards your project classpath. hither is total code example:
import com.google.common.io.CharStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* How to convert InputStream into String inwards Java using Google's Guava library
*/
public class InputStreamToString{
public static void main(String args[]) throws UnsupportedEncodingException, IOException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
System.out.println(stringFromStream);
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* How to convert InputStream into String inwards Java using Google's Guava library
*/
public class InputStreamToString{
public static void main(String args[]) throws UnsupportedEncodingException, IOException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
System.out.println(stringFromStream);
}
}
How to read InputStream into String alongside IOUtils.copy together with StringWriter class
java.io.StringWriter is about other convenient agency of reading writing Strings together with yesteryear using IOUtils.copy() yous tin copy contents cast InputStream to reader, Here is a consummate code representative of reading InputStream every bit String using StringWriter:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;
/**
* Java Program to demonstrate reading of InputStream every bit String
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;
/**
* Java Program to demonstrate reading of InputStream every bit String
* using StringWriter together with Apache IOUtils
*/
public class InputStreamToStringConversion{
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
StringWriter author = new StringWriter();
String encoding = "UTF-8";
IOUtils.copy(fis, writer, encoding);
System.out.println(writer.toString());
}
}
*/
public class InputStreamToStringConversion{
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
FileInputStream fis = new FileInputStream("c:/sample.txt");
StringWriter author = new StringWriter();
String encoding = "UTF-8";
IOUtils.copy(fis, writer, encoding);
System.out.println(writer.toString());
}
}
That's all on converting InputStream to String inwards Java yesteryear using measure center coffee library together with yesteryear using opened upward rootage Apache common IOUtils together with Google's guava libraries. Don't forget Character encoding when converting bytes to String which is instance hither likewise brand a convenient selection every bit sometime adding additional library for i functionality is non the best option. permit us know if yous know whatever other agency of converting InputStream to String inwards Java.
Further Learning
Complete Java Masterclass
How to parse XML file inwards Java using DOM parser