Read/Convert an inputStream to a String

 
 

Share on Google+Share on Google+

Java Coder
Read/Convert an inputStream to a String
3 Answer(s)      7 months ago
Posted in : Java Beginners

Hi,

I have an input stream in Java and convert it to a String. what is the best code for for this?

How to Read/Convert an inputStream to a String?

My object is of java.io.InputStream class.

Thanks

Ads
View Answers

April 24, 2017 at 5:23 PM


Hi,

The best method is to use the org.apache.commons.io.IOUtils class which provides methods for converting stream into a String.

Add Maven dependency in your pom.xml:

  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
  </dependency>

Now you can use the commons-io library in code. Here is the full code of Reading /Converting an inputStream to a String.

package net.roseindia;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;

public class InputStreamToString {

    public static void main(String[] args) {
        //Construct simple input stream 
        //Input stream can be from file or other source also
        //and it will work
        String str = "Learn Java at http://www.roseindia.net";
        //Convert String into InputStream
        InputStream inputStream = new ByteArrayInputStream(str.getBytes());

        StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(inputStream, writer, "UTF-8");
        } catch (IOException e) {

            e.printStackTrace();
        }
        String theString = writer.toString();

        System.out.println("String Value: "+theString);
    }

}

First create StringWriter:

StringWriter writer = new StringWriter();

Then copy the stream into writer:

IOUtils.copy(inputStream, writer, "UTF-8");

Get String from writer:

String theString = writer.toString();

Thanks



April 24, 2017 at 5:27 PM


Hi,

You can also Read/Convert an inputStream to a String with Scanner class. Here is the full code for the conversion:

package net.roseindia;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Scanner;

import org.apache.commons.io.IOUtils;

public class InputStreamToStringWithScanner {

    public static void main(String[] args) {
        //Construct simple input stream 
        //Input stream can be from file or other source also
        //and it will work
        String str = "Learn Java at http://www.roseindia.net";
        //Convert String into InputStream
        InputStream inputStream = new ByteArrayInputStream(str.getBytes());

        String inputStreamString = new Scanner(inputStream,"UTF-8").useDelimiter("\\A").next();
        System.out.println(inputStreamString);

    }

}

Thanks



April 24, 2017 at 5:43 PM


Hi,

In Pure Java you can use following classes:

  • StringBuilder

  • BufferedReader

classes for converting stream into String.

Here is full source code that you may try:

package net.roseindia;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import org.apache.commons.io.IOUtils;

public class InputStreamToStringWithScanner {

    public static void main(String[] args) {
        //Construct input stream
        String str = "Learn Java at http://www.roseindia.net";
        InputStream inputStream = new ByteArrayInputStream(str.getBytes());

        StringBuilder inputStringBuilder = new StringBuilder();

        BufferedReader bufferedReader;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            String line = bufferedReader.readLine();
            while (line != null) {
                inputStringBuilder.append(line);
                inputStringBuilder.append('\n');
                line = bufferedReader.readLine();
            }
            System.out.println(inputStringBuilder.toString());

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

    }

}

Thanks


Ads









Related Tutorials/Questions & Answers:
Read/Convert an inputStream to a String
to Read/Convert an inputStream to a String? My object is of java.io.InputStream...Read/Convert an inputStream to a String  Hi, I have an input stream...://www.roseindia.net"; //Convert String into InputStream InputStream
Java convert string to InputStream
Java convert string to InputStream In this section, you will learn how to convert string to Inputstream. In one of the previous sections, we have discussed the conversion of InputStream to string. Here we are going to do just reverse
Advertisements
How to convert Input Stream to String in java
How to convert Input Stream to String in java The InputStream class... InputStream into string.  Description of code: Since class... by taking the file through FileInputStream. The read() method of an InputStream
Java URL inputstream caching
Java URL inputstream caching  I have a web application in which... always i wanted to cache the results of the URL inputstream and refresh it for every...); //connection.setReadTimeout(1000); //connection.setConnectTimeout(1000); InputStream inStream
Convert Inputstream to ByteArrayInputStream
Convert Inputstream to ByteArrayInputStream       In this example we are going to convert.... Then convert this input stream into string and then string into byte by using
Java IO InputStream Example
to read data input stream using the InputStream. To read the input stream we must have a source from where the stream can be read by the InputStream so I have... created a reference of InputStream and used the FileInputStream to read the data
Java Write To InputStream
WriteToInputStream { public static void main(String args[]) { InputStream...Java Write To InputStream In this tutorial you will learn how to write to InputStream in java. Write to file from InputStream in java you may use
Convert InputStream to File
Convert InputStream to File       Here we are showing how to convert an InputStream to File. To do so first read the file as InputStream 
Convert InputStream to BufferedReader
Convert InputStream to BufferedReader       In this example we are going to convert...; into InputStreamReader  and finally we convert the InputStream into BufferedReader
How to write file from inputstream in java
How to write file from inputstream in java  Hi, how to write file from inputstream in java program. Plz suggest an example or suggested link... link to your query "How to Write to inputStream in Java". This is good
STRING.....
STRING.....  plzz sent me d code for counting vowels in a string... gui programme
string
string   difference detween "public static void main (String[] args) " and "public static void main (String args[])" in java but it executes both... "String args[]" can mean a "string array called args which is an array
string
string  String helloString = new String(helloArray); System.out.println(helloString); i am unable to understand this. could u plz explain
String
String  how to add spaces with string functions.?   Hi... String addSpaceToRight(String s, int n) { return String.format("%1$-" + n + "s", s); } public static String addSpaceToLeft(String s, int n) { return
string
string  a java program using string function to input any string... ArrangeStringAlphabetically { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter string
String
characters in string?   import java.util.*; class RemoveDuplicateCharatcersFromString { public static String removeDuplicates(String s... < s.length(); i++) { String st = s.substring(i, i + 1
String
String  write down the code of remove any character from a given string without using any string function   please give me the code of remove any given character from a given string without using function
string
ExtractWords { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter String: "); String st=input.nextLine(); String str[]=st.split(" "); for(int i=0
string
string  a java program to input a string and display the string...*; import java.io.*; public class FirstLetter{ public static String capitalizeFirstLetter( String str ) { final StringTokenizer st = new StringTokenizer( str
string
string   just i want to a program in a short form to the given string in buffered reader for example input string: Suresh Chandra Gupta output: S. C...; public class StringTest { public static void main(String [] args
string
string  write a program to accept the string and store the reverse stream into another array and print
string
string  java prgm to find total occurence of a given string pattern in a sentence
string
string  java prgm to find total occurence of a given string pattern in a sentence
String
String  write a program using string it should replace 'c'char to integer number as 1 in whole source
String
String  How to Convert sunnapu gopal to Sunnapu Gopal in java using String
String
String  how to print in between numbers if the question "String s = "1,2,3,4,5,6,8,-25"" out must be 1 2,3,4,5,6,7,8,9,10,upto25
string
and also displaying that contain word? Like I want to find "a" in the string... and a character. It then count the occurrence of that character in the string and display... String_Example { public static void main(String[] args
string
string  program for String reverse and replace in c,c++,java e.g.Input:10,20,hello output:hello;20;10   Hi Friend, Try the following java...(String[] args) { String array[]=new String[5]; Scanner input
string
string  a java program using string function that computes your initials from your full name and display them   Please visit the following links: http://www.roseindia.net/tutorial/java/core/printInitials.html http
string
string  a java program using string function and access modifiers to automate the insurance company which will have to manage the information about policy holders Data Members: 1)Policy No 2)Name of policy holder 3)Address 4
(ii) String and String Buffer Class
(ii) String and String Buffer Class  difference between String and String Buffer Class

Ads

 
Advertisement null

Ads