5 Ways To Convert Inputstream To String Inward Java

InputStream to String Conversion Example
Converting InputStream to String inward Java has buy the farm rattling tardily after introduction of Scanner class inward Java five in addition to due to evolution of several opened upward origin libraries similar Apache green IOUtils in addition to Google Open origin guava-libraries which provides first-class back upward to convert InputStream to String inward Java program. nosotros often remove to convert InputStream to String  while working inward Java for illustration if yous are reading XML files from InputStream in addition to later on performing XSLT transformation on it or if InputStream is reading information from text file or text input Source in addition to nosotros either desire to log  Strings inward log file or desire to operate on whole String. Before Java five yous would direct maintain to write lots of boiler plate code to read String describe of piece of employment past times line or byte past times byte depending upon whether yous are using either BufferedReader or non but equally I said since JDK five added Scanner for reading input, its fairly tardily to convert InputStream into String.


Before Converting whatsoever InputStream or ByteStream into String don't forget to render character encoding or charSet which tells Java Which characters to human face from those streams of bytes. inward the absence of right grapheme encoding yous mightiness alter the output because same bytes tin hold upward used to stand upward for dissimilar grapheme inward dissimilar encoding. Another matter to proceed inward heed is that if yous don't render grapheme encoding, Default grapheme encoding inward Java volition hold upward used which tin hold upward specified from System holding "file.encoding" or "UTF-8" if file.encoding is non specified. In this Java tutorial nosotros volition encounter five dissimilar illustration of converting InputStream to String inward Java both past times using measure JDK libraries in addition to using opened upward origin libraries.

How to convert InputStream to String inward Java – five Examples

here are dissimilar ways to convert InputStream to String inward Java, initiative of all nosotros volition encounter close unproblematic agency of reading InputStream equally String.


InputStream to String -  Using Java five Scanner
constructor which convey an InputStream, a grapheme encoding in addition to a delimiter to read String from InputStream. Here nosotros direct maintain used delimiter equally "\A" which is boundary tally for initiative of all of  the input equally declared inward java.util.regex.Pattern in addition to that's why Scanner is returning whole String cast InputStream. I oft utilization this technique to read input from user inward Java using System.in which is close mutual illustration of InputStream inward Java, but equally demonstrated hither this tin too hold upward used to read text file inward Java.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Java plan illustration to demonstrate How to convert InputStream into String past times using JDK
 * Scanner utility. This plan volition piece of employment Java five onwards equally Scanner was added inward 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 past times changing InputStream to String inward Java.

If yous desire to encounter how an wrong grapheme encoding completely changes the String merely alter the grapheme encoding cast "UTF-8" to "UTF-16" in addition to yous encounter Chinese(may be) characters instead of English.

Output:
?????????????!???????????!??????^(4)????????

Convert InputStream to String - Plain quondam JDK4 Example
If yous nonetheless remove to do it on obviously quondam Java on JDK4 without including whatsoever additional dependency inward your PATH in addition to Classpath than hither is quick illustration using BufferedReader in Java, Remember yous tin too do this past times reading byte past times byte from InputStream but that's rattling ho-hum then take in using BufferedReader for improve surgery fifty-fifty if yous code on JDK4 . For to a greater extent than surgery tips encounter my post service 4 JDBC surgery tips inward Java program. Let’s encounter illustration of converting InputStream to String using BufferedReader inward Java.

/**
 * Java plan to demonstrate How to read InputStream equally String
 * using BufferedReader in addition to StringBuilder inward Java.
 * This is quondam in addition to measure agency of converting an InputStream into String inward 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 describe of piece of employment = bufferedReader.readLine();
        while(line != null){
            inputStringBuilder.append(line);inputStringBuilder.append('\n');
            describe of piece of employment = bufferedReader.readLine();
        }
        System.out.println(inputStringBuilder.toString());

}
Output:
This String is read from InputStream past times changing InputStream to String inward Java.
second line


This is practiced obviously quondam Java method of converting InputStream to String without adding whatsoever extra dependency but recall its converting \r to \n because nosotros are reading describe of piece of employment past times line, which inward close cases fine.

Read InputStream to String - Using Apache IOUtils library
As I said before in that place are many opened upward origin library inward Java which makes coding lot to a greater extent than easier than whatsoever other language. Here is code illustration for How to convert InputStream to String inward Java using Apache IOUtils

/**
 * Example of How to read InputStream into String past times using Apache IOUtils library.
 * Nice in addition to laid clean agency of getting InputStream equally String inward 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 inward Java, merely ane describe of piece of employment of code in addition to that does convey assist of grapheme encoding equally well..

InputStream to String - Using Google's guava-libraries
Google has opened upward origin its ain laid of Java libraries they utilization for Java development within Google. it has lots of utility business office in addition to too complements Apache green 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 remove to include guava library i.e. guava-11.0.1.jar inward 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 inward 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 amongst IOUtils.copy in addition to StringWriter class
java.io.StringWriter is or then other convenient agency of reading writing Strings in addition to past times using IOUtils.copy() yous tin copy contents cast InputStream to reader, Here is a consummate code illustration of reading InputStream equally 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 equally String
  * using StringWriter in addition to 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());
    }
}

That's all on converting InputStream to String inward Java past times using measure substance coffee library in addition to past times using opened upward origin Apache green IOUtils in addition to Google's guava libraries. Don't forget Character encoding when converting bytes to String which is illustration hither too brand a convenient alternative equally sometime adding additional library for ane functionality is non the best option. allow us know if yous know whatsoever other agency of converting InputStream to String inward Java.

Further Learning
Complete Java Masterclass
How to parse XML file inward Java using DOM parser

Belum ada Komentar untuk "5 Ways To Convert Inputstream To String Inward Java"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel