Johnny Maelstrom
Johnny Maelstrom

Reputation: 48451

How do I read / convert an InputStream into a String in Java?

If you have a java.io.InputStream object, how should you process that object and produce a String?


Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) {
// ???
}

Upvotes: 4759

Views: 2748948

Answers (30)

Alireza
Alireza

Reputation: 104870

In short, think of an InputStream like a conveyor belt of raw materials:

The InputStreamReader is a machine that translates those raw materials into parts (characters).

The BufferedReader is a storage area that batches parts for efficiency. The Stream and Collectors.joining() assemble the parts into the final product (a String).

This is how Java processes streams behind the scenes to give you a String!

Here is an example of how we can do it:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public String convertStreamToString(InputStream is) {
    if (is == null) return "";
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
        return reader.lines().collect(Collectors.joining(System.lineSeparator()));
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

Upvotes: 0

Chinnery
Chinnery

Reputation: 10229

Apache Commons allows:

String myString = IOUtils.toString(myInputStream, "UTF-8");

Of course, you could choose other character encodings besides UTF-8.

Note: From Java versions 1.7 and upwards, you can use StandardCharsets class for charsets instead of hardcoding as "UTF-8".(ex: StandardCharsets.UTF_8)

Also see: (documentation)

Upvotes: 893

Anurath Mane
Anurath Mane

Reputation: 47

In Java 8 user lines() which return string on that we can perform collect(Collectors.joining())

Actual code is as below.

new BufferedReader(new InputStreamReader(System.in)).lines().collect(Collectors.joining());

Upvotes: 3

Prabhat Kumar
Prabhat Kumar

Reputation: 17

Use java.util.Scanner to read InputStream into a String:

String result = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining("\n"));

Upvotes: 1

Jon Moore
Jon Moore

Reputation: 1420

Use:

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;

public static String readInputStreamAsString(InputStream in)
    throws IOException {

    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
        byte b = (byte)result;
        buf.write(b);
        result = bis.read();
    }
    return buf.toString();
}

Upvotes: 82

Hai Zhang
Hai Zhang

Reputation: 5852

This is an answer adapted from org.apache.commons.io.IOUtils source code, for those who want to have the Apache implementation, but do not want the whole library.

private static final int BUFFER_SIZE = 4 * 1024;

public static String inputStreamToString(InputStream inputStream, String charsetName)
        throws IOException {
    StringBuilder builder = new StringBuilder();
    InputStreamReader reader = new InputStreamReader(inputStream, charsetName);
    char[] buffer = new char[BUFFER_SIZE];
    int length;
    while ((length = reader.read(buffer)) != -1) {
        builder.append(buffer, 0, length);
    }
    return builder.toString();
}

Upvotes: 24

gil.fernandes
gil.fernandes

Reputation: 14621

This solution to this question is not the simplest, but since NIO streams and channels have not been mentioned, here goes a version which uses NIO channels and a ByteBuffer to convert a stream into a string.

public static String streamToStringChannel(InputStream in, String encoding, int bufSize) throws IOException {
    ReadableByteChannel channel = Channels.newChannel(in);
    ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    WritableByteChannel outChannel = Channels.newChannel(bout);
    while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {
        byteBuffer.flip();  //make buffer ready for write
        outChannel.write(byteBuffer);
        byteBuffer.compact(); //make buffer ready for reading
    }
    channel.close();
    outChannel.close();
    return bout.toString(encoding);
}

Here is an example how to use it:

try (InputStream in = new FileInputStream("/tmp/large_file.xml")) {
    String x = streamToStringChannel(in, "UTF-8", 1);
    System.out.println(x);
}

The performance of this method should be good for large files.

Upvotes: 1

Harsh
Harsh

Reputation: 3009

InputStream  inputStream = null;
BufferedReader bufferedReader = null;
try {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String stringBuilder = new StringBuilder();
    String content;
    while((content = bufferedReader.readLine()) != null) {
        stringBuilder.append(content);
    }
    System.out.println("content of file::" + stringBuilder.toString());
}
catch (IOException e) {
    e.printStackTrace();
}
finally {
    if(bufferedReader != null) {
        try {
            bufferedReader.close();
        }
        catch(IoException ex) {
           ex.printStackTrace();
        }

Upvotes: 2

Alex
Alex

Reputation: 8493

Kotlin users simply do:

println(InputStreamReader(is).readText())

whereas

readText()

is the Kotlin standard library’s built-in extension method.

Upvotes: 17

Daniel De León
Daniel De León

Reputation: 13679

This one is nice because:

  • It safely handles the Charset.
  • You control the read buffer size.
  • You can provision the length of the builder and it doesn't have to be an exact value.
  • Is free from library dependencies.
  • Is for Java 7 or higher.

How to do it

public static String convertStreamToString(InputStream is) throws IOException {
   StringBuilder sb = new StringBuilder(2048); // Define a size if you have an idea of it.
   char[] read = new char[128]; // Your buffer size.
   try (InputStreamReader ir = new InputStreamReader(is, StandardCharsets.UTF_8)) {
     for (int i; -1 != (i = ir.read(read)); sb.append(read, 0, i));
   }
   return sb.toString();
}

For JDK 9

public static String inputStreamString(InputStream inputStream) throws IOException {
    try (inputStream) {
        return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    }
}

Upvotes: 24

Dinis Cruz
Dinis Cruz

Reputation: 4289

I had Log4j available, so I was able to use the org.apache.log4j.lf5.util.StreamUtils.getBytes method to get the bytes, which I was able to convert into a string using the String constructor:

String result = new String(StreamUtils.getBytes(inputStream));

Upvotes: -1

Ben Barkay
Ben Barkay

Reputation: 5632

I have written a class that does just that. Sometimes you don't want to add Apache Commons just for one thing, and want something dumber than Scanner that doesn't examine the content.

Usage is as follows

// Read from InputStream
String data = new ReaderSink(inputStream, Charset.forName("UTF-8")).drain();

// Read from File
data = new ReaderSink(file, Charset.forName("UTF-8")).drain();

// Drain input stream to console
new ReaderSink(inputStream, Charset.forName("UTF-8")).drainTo(System.out);

Here is the code for ReaderSink:

import java.io.*;
import java.nio.charset.Charset;

/**
 * A simple sink class that drains a {@link Reader} to a {@link String} or
 * to a {@link Writer}.
 *
 * @author Ben Barkay
 * @version 2/20/2014
 */
public class ReaderSink {
    /**
     * The default buffer size to use if no buffer size was specified.
     */
    public static final int DEFAULT_BUFFER_SIZE = 1024;

    /**
     * The {@link Reader} that will be drained.
     */
    private final Reader in;

    /**
     * Constructs a new {@code ReaderSink} for the specified file and charset.
     * @param file      The file to read from.
     * @param charset   The charset to use.
     * @throws FileNotFoundException    If the file was not found on the filesystem.
     */
    public ReaderSink(File file, Charset charset) throws FileNotFoundException {
        this(new FileInputStream(file), charset);
    }

    /**
     * Constructs a new {@code ReaderSink} for the specified {@link InputStream}.
     * @param in        The {@link InputStream} to drain.
     * @param charset   The charset to use.
     */
    public ReaderSink(InputStream in, Charset charset) {
        this(new InputStreamReader(in, charset));
    }

    /**
     * Constructs a new {@code ReaderSink} for the specified {@link Reader}.
     * @param in    The reader to drain.
     */
    public ReaderSink(Reader in) {
        this.in = in;
    }

    /**
     * Drains the data from the underlying {@link Reader}, returning a {@link String} containing
     * all of the read information. This method will use {@link #DEFAULT_BUFFER_SIZE} for
     * its buffer size.
     * @return  A {@link String} containing all of the information that was read.
     */
    public String drain() throws IOException {
        return drain(DEFAULT_BUFFER_SIZE);
    }

    /**
     * Drains the data from the underlying {@link Reader}, returning a {@link String} containing
     * all of the read information.
     * @param bufferSize    The size of the buffer to use when reading.
     * @return  A {@link String} containing all of the information that was read.
     */
    public String drain(int bufferSize) throws IOException {
        StringWriter stringWriter = new StringWriter();
        drainTo(stringWriter, bufferSize);
        return stringWriter.toString();
    }

    /**
     * Drains the data from the underlying {@link Reader}, writing it to the
     * specified {@link Writer}. This method will use {@link #DEFAULT_BUFFER_SIZE} for
     * its buffer size.
     * @param out   The {@link Writer} to write to.
     */
    public void drainTo(Writer out) throws IOException {
        drainTo(out, DEFAULT_BUFFER_SIZE);
    }

    /**
     * Drains the data from the underlying {@link Reader}, writing it to the
     * specified {@link Writer}.
     * @param out           The {@link Writer} to write to.
     * @param bufferSize    The size of the buffer to use when reader.
     */
    public void drainTo(Writer out, int bufferSize) throws IOException {
        char[] buffer = new char[bufferSize];
        int read;
        while ((read = in.read(buffer)) > -1) {
            out.write(buffer, 0, read);
        }
    }
}

Upvotes: 5

Rys
Rys

Reputation: 5164

You can use Apache Commons.

In the IOUtils you can find the toString method with three helpful implementations.

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input) throws IOException {
        return toString(input, Charset.defaultCharset());
}

public static String toString(InputStream input, String encoding)
            throws IOException {
        return toString(input, Charsets.toCharset(encoding));
}

Upvotes: 4

TG Gowda
TG Gowda

Reputation: 11957

Make sure to close the streams at the end if you use Stream Readers

private String readStream(InputStream iStream) throws IOException {

    // Build a Stream Reader, it can read character by character
    InputStreamReader iStreamReader = new InputStreamReader(iStream);

    // Build a buffered Reader, so that I can read whole line at once
    BufferedReader bReader = new BufferedReader(iStreamReader);
    String line = null;
    StringBuilder builder = new StringBuilder();
    while((line = bReader.readLine()) != null) {  // Read till end
        builder.append(line);
        builder.append("\n"); // Append new line to preserve lines
    }
    bReader.close();         // Close all opened stuff
    iStreamReader.close();
    //iStream.close(); // Let the creator of the stream close it!
                       // some readers may auto close the inner stream
    return builder.toString();
}

On JDK 7+, you can use try-with-resources construct.

/**
 * Reads the stream into a string
 * @param iStream the input stream
 * @return the string read from the stream
 * @throws IOException when an IO error occurs
 */
private String readStream(InputStream iStream) throws IOException {

    // Buffered reader allows us to read line by line
    try (BufferedReader bReader =
                 new BufferedReader(new InputStreamReader(iStream))) {
        StringBuilder builder = new StringBuilder();
        String line;
        while((line = bReader.readLine()) != null) {  // Read till end
            builder.append(line);
            builder.append("\n"); // Append new line to preserve lines
        }
        return builder.toString();
    }
}

Upvotes: 22

Raghu K Nair
Raghu K Nair

Reputation: 3942

The easiest way in JDK is with the following code snippets.

String convertToString(InputStream in) {
    String resource = new Scanner(in).useDelimiter("\\Z").next();
    return resource;
}

Upvotes: 10

TKH
TKH

Reputation: 838

Here's more-or-less sampath's answer, cleaned up a bit and represented as a function:

String streamToString(InputStream in) throws IOException {
  StringBuilder out = new StringBuilder();
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  for (String line = br.readLine(); line != null; line = br.readLine())
    out.append(line);
  br.close();
  return out.toString();
}

Upvotes: 31

Slava Vedenin
Slava Vedenin

Reputation: 60174

To summarize the other answers, I found 11 main ways to do this (see below). And I wrote some performance tests (see results below):

Ways to convert an InputStream to a String:

  1. Using IOUtils.toString (Apache Utils)

     String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    
  2. Using CharStreams (Guava)

     String result = CharStreams.toString(new InputStreamReader(
           inputStream, Charsets.UTF_8));
    
  3. Using Scanner (JDK)

     Scanner s = new Scanner(inputStream).useDelimiter("\\A");
     String result = s.hasNext() ? s.next() : "";
    
  4. Using Stream API (Java 8). Warning: This solution converts different line breaks (like \r\n) to \n.

     String result = new BufferedReader(new InputStreamReader(inputStream))
       .lines().collect(Collectors.joining("\n"));
    
  5. Using parallel Stream API (Java 8). Warning: This solution converts different line breaks (like \r\n) to \n.

     String result = new BufferedReader(new InputStreamReader(inputStream))
        .lines().parallel().collect(Collectors.joining("\n"));
    
  6. Using InputStreamReader and StringBuilder (JDK)

     int bufferSize = 1024;
     char[] buffer = new char[bufferSize];
     StringBuilder out = new StringBuilder();
     Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
     for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
         out.append(buffer, 0, numRead);
     }
     return out.toString();
    
  7. Using StringWriter and IOUtils.copy (Apache Commons)

     StringWriter writer = new StringWriter();
     IOUtils.copy(inputStream, writer, "UTF-8");
     return writer.toString();
    
  8. Using ByteArrayOutputStream and inputStream.read (JDK)

     ByteArrayOutputStream result = new ByteArrayOutputStream();
     byte[] buffer = new byte[1024];
     for (int length; (length = inputStream.read(buffer)) != -1; ) {
         result.write(buffer, 0, length);
     }
     // StandardCharsets.UTF_8.name() > JDK 7
     return result.toString("UTF-8");
    
  9. Using BufferedReader (JDK). Warning: This solution converts different line breaks (like \n\r) to line.separator system property (for example, in Windows to "\r\n").

     String newLine = System.getProperty("line.separator");
     BufferedReader reader = new BufferedReader(
             new InputStreamReader(inputStream));
     StringBuilder result = new StringBuilder();
     for (String line; (line = reader.readLine()) != null; ) {
         if (result.length() > 0) {
             result.append(newLine);
         }
         result.append(line);
     }
     return result.toString();
    
  10. Using BufferedInputStream and ByteArrayOutputStream (JDK)

    BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    for (int result = bis.read(); result != -1; result = bis.read()) {
        buf.write((byte) result);
    }
    // StandardCharsets.UTF_8.name() > JDK 7
    return buf.toString("UTF-8");
    
  11. Using inputStream.read() and StringBuilder (JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)

    StringBuilder sb = new StringBuilder();
    for (int ch; (ch = inputStream.read()) != -1; ) {
        sb.append((char) ch);
    }
    return sb.toString();
    

Warning:

  1. Solutions 4, 5 and 9 convert different line breaks to one.

  2. Solution 11 can't work correctly with Unicode text

Performance tests

Performance tests for small String (length = 175), url in github (mode = Average Time, system = Linux, score 1,343 is the best):

              Benchmark                         Mode  Cnt   Score   Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   1,343 ± 0,028  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   6,980 ± 0,404  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   7,437 ± 0,735  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10   8,977 ± 0,328  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10  10,613 ± 0,599  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10  10,605 ± 0,527  us/op
 3. Scanner (JDK)                               avgt   10  12,083 ± 0,293  us/op
 2. CharStreams (guava)                         avgt   10  12,999 ± 0,514  us/op
 4. Stream Api (Java 8)                         avgt   10  15,811 ± 0,605  us/op
 9. BufferedReader (JDK)                        avgt   10  16,038 ± 0,711  us/op
 5. parallel Stream Api (Java 8)                avgt   10  21,544 ± 0,583  us/op

Performance tests for big String (length = 50100), url in github (mode = Average Time, system = Linux, score 200,715 is the best):

               Benchmark                        Mode  Cnt   Score        Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   200,715 ±   18,103  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10   300,019 ±    8,751  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   347,616 ±  130,348  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10   352,791 ±  105,337  us/op
 2. CharStreams (guava)                         avgt   10   420,137 ±   59,877  us/op
 9. BufferedReader (JDK)                        avgt   10   632,028 ±   17,002  us/op
 5. parallel Stream Api (Java 8)                avgt   10   662,999 ±   46,199  us/op
 4. Stream Api (Java 8)                         avgt   10   701,269 ±   82,296  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   740,837 ±    5,613  us/op
 3. Scanner (JDK)                               avgt   10   751,417 ±   62,026  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10  2919,350 ± 1101,942  us/op

Graphs (performance tests depending on Input Stream length in Windows 7 system)
enter image description here

Performance test (Average Time) depending on Input Stream length in Windows 7 system:

 length  182    546     1092    3276    9828    29484   58968

 test8  0.38    0.938   1.868   4.448   13.412  36.459  72.708
 test4  2.362   3.609   5.573   12.769  40.74   81.415  159.864
 test5  3.881   5.075   6.904   14.123  50.258  129.937 166.162
 test9  2.237   3.493   5.422   11.977  45.98   89.336  177.39
 test6  1.261   2.12    4.38    10.698  31.821  86.106  186.636
 test7  1.601   2.391   3.646   8.367   38.196  110.221 211.016
 test1  1.529   2.381   3.527   8.411   40.551  105.16  212.573
 test3  3.035   3.934   8.606   20.858  61.571  118.744 235.428
 test2  3.136   6.238   10.508  33.48   43.532  118.044 239.481
 test10 1.593   4.736   7.527   20.557  59.856  162.907 323.147
 test11 3.913   11.506  23.26   68.644  207.591 600.444 1211.545

Upvotes: 3580

Zufar Sunagatov
Zufar Sunagatov

Reputation: 1316

How do I read / convert an InputStream into a String in Java?

You would provide one more possible solution where performance is the main concern, you can improve speed by using a BufferedReader to read the InputStream line by line, instead of reading the InputStream byte by byte. Here it is a code:

public String convertStreamToString(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        stringBuilder.append(line).append("\n");
    }
    return stringBuilder.toString();
}

When compared to reading the input byte by byte, this method buffers the information and reads it in chunks, which can greatly improve performance.

Upvotes: 1

DJDaveMark
DJDaveMark

Reputation: 2855

If you can't use Commons IO (FileUtils, IOUtils, and CopyUtils), here's an example using a BufferedReader to read the file line by line:

public class StringFromFile {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFile.class.getResourceAsStream("file.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is/*, "UTF-8"*/));
        final int CHARS_PER_PAGE = 5000; //counting spaces
        StringBuilder builder = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(String line=br.readLine(); line!=null; line=br.readLine()) {
                builder.append(line);
                builder.append('\n');
            }
        }
        catch (IOException ignore) { }

        String text = builder.toString();
        System.out.println(text);
    }
}

Or if you want raw speed, I'd propose a variation on what Paul de Vrieze suggested (which avoids using a StringWriter (which uses a StringBuffer internally):

public class StringFromFileFast {
    public static void main(String[] args) /*throws UnsupportedEncodingException*/ {
        InputStream is = StringFromFileFast.class.getResourceAsStream("file.txt");
        InputStreamReader input = new InputStreamReader(is/*, "UTF-8"*/);
        final int CHARS_PER_PAGE = 5000; //counting spaces
        final char[] buffer = new char[CHARS_PER_PAGE];
        StringBuilder output = new StringBuilder(CHARS_PER_PAGE);
        try {
            for(int read = input.read(buffer, 0, buffer.length);
                    read != -1;
                    read = input.read(buffer, 0, buffer.length)) {
                output.append(buffer, 0, read);
            }
        } catch (IOException ignore) { }

        String text = output.toString();
        System.out.println(text);
    }
}

Upvotes: 30

chubbsondubs
chubbsondubs

Reputation: 38867

I see a lot of just snippets but zero explanations as to WHY this the snippet is a good way. I'm going to limit myself to just plain Java. What's key to understand about Java:

  • java.io.InputStream is for reading bytes.
  • java.io.Reader is for reading character data.

You should NOT be reading InputStream and converting that to Strings yourself because the world we are in isn't single byte focused anymore. And this is where java.nio.charset.Charset objects come into play. Charset classes convert bytes -> char. They bridge java.io.InputStream and java.io.Reader. You have to have java.nio.charset.Charset to convert InputStream into a Reader.

I'm going to do this the low memory usage way (Well until you read the thing into a single string which will eat up the full memory, but dems the requirements ;-)

Here's the code:

public String readString(InputStream inStream) {
   char[] buffer = new char[2**16];
   try( Reader reader = new InputStreamReader( inStream, "UTF-8") ) {
      int length = -1;
      StringBuilder builder = new StringBuilder();
      while( (length = reader.read( buffer, 0, buffer.length )) >= 0 ) {
          builder.append( buffer, 0, length );
      }
   }
   return builder.toString();
}

The key here is to use InputStreamReader to bridge between InputStream -> Reader where you can read character data. From there it's simple to build the string using a StringBuilder. Another important part of InputStreamReader is specifying the character encoding. In this case I used "UTF-8", but it could be "ISO-8859-1" or "UTF-16", etc.

Word to the wise. I didn't use BufferedInputStream or BufferedReader to wrap these. Those classes are overused. If you are calling Reader.read( char[], int start, int len) or other array read methods then you are providing a buffer. Your usage is mostly optimized (the size of the buffer is what is in question) There is no need to have BufferedInputStream create yet another buffer for you. You've allocated your buffer so there is zero advantage added by wrapping your InputStream in a BufferedInputStream. Now if you are calling InputStream.read() or Reader.read() then yes those classes are providing a speed boost by converting single byte/char reads into buffered reads. But most of the time people don't read byte by byte.

The only exception to that advice is if you want to use readLine in which case BufferedReader is your friend, and go right ahead and use it. A word of caution is in order. If you are reading a 1GB one line file it's going to take over 1GB of memory to read your file which is probably NOT what you want.

That's the tightest loop with minimal memory usage for reading the actual data. And that's why reading the full data into a String might not always be the best approach, but this code can be adapted to other situations. If you were write it out to a java.io.Writer that streamed it out to an external storage it'd be very tight.

Upvotes: 0

drakeet
drakeet

Reputation: 2714

With Okio:

String result = Okio.buffer(Okio.source(inputStream)).readUtf8();

Upvotes: 4

user12402945
user12402945

Reputation:

This code is for new Java learners:

private String textDataFromFile;

public String getFromFile(InputStream myInputStream) throws FileNotFoundException, IOException {

    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(myInputStream));

    StringBuilder stringBuilder = new StringBuilder();

    String eachStringLine;

    while ((eachStringLine = bufferReader.readLine()) != null) {
        stringBuilder.append(eachStringLine).append("\n");
    }
    textDataFromFile = stringBuilder.toString();

    return textDataFromFile;
}

Upvotes: 5

Kaplan
Kaplan

Reputation: 3758

If you need to convert the string to a specific character set without external libraries then:

public String convertStreamToString(InputStream is) throws IOException {
  try (ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
    is.transferTo(baos);
    return baos.toString(StandardCharsets.UTF_8);
  }
}

Upvotes: 3

somayaj
somayaj

Reputation: 54

The easiest way, a one-liner:

public static void main(String... args) throws IOException {
    System.out.println(new String(Files.readAllBytes(Paths.get("csv.txt"))));
}

Upvotes: -5

Harry Lime
Harry Lime

Reputation: 29576

A nice way to do this is using Apache Commons IOUtils to copy the InputStream into a StringWriter... Something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or even

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers.

Upvotes: 2760

hertzsprung
hertzsprung

Reputation: 9903

If you're using AWS SDK v2, call IoUtils.toUtf8String():

public String convertStreamToString(InputStream is) {
    return IoUtils.toUtf8String(is);
}

Upvotes: 1

hyperneutrino
hyperneutrino

Reputation: 5425

Note: This probably isn't a good idea. This method uses recursion and thus will hit a StackOverflowError very quickly:

public String read (InputStream is) {
    byte next = is.read();
    return next == -1 ? "" : next + read(is); // Recursive part: reads next byte recursively
}

Upvotes: -5

Tagir Valeev
Tagir Valeev

Reputation: 100289

For completeness here is Java 9 solution:

public static String toString(InputStream input) throws IOException {
    return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}

This uses the readAllBytes method which was added to Java 9.

Upvotes: 192

czerny
czerny

Reputation: 16684

String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
    try (
            final StringWriter writer = new StringWriter();
            final InputStreamReader reader = new InputStreamReader(inputStream, charset)
        ) {
        reader.transferTo(writer);
        return writer.toString();
    }
}

Upvotes: 22

13hola
13hola

Reputation: 170

I have created this code, and it works. There are no required external plug-ins.

There is a converter String to Stream and Stream to String:

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class STRINGTOSTREAM {

    public static void main(String[] args)
    {
        String text = "Hello Bhola..!\nMy Name Is Kishan ";

        InputStream strm = new ByteArrayInputStream(text.getBytes());    // Convert String to Stream

        String data = streamTostring(strm);

        System.out.println(data);
    }

    static String streamTostring(InputStream stream)
    {
        String data = "";

        try
        {
            StringBuilder stringbuld = new StringBuilder();
            int i;
            while ((i=stream.read())!=-1)
            {
                stringbuld.append((char)i);
            }
            data = stringbuld.toString();
        }
        catch(Exception e)
        {
            data = "No data Streamed.";
        }
        return data;
    }

Upvotes: 2

Related Questions