Java InputStream Read by Charset inputStreamToString(final InputStream inputStream, final String charsetName)

Here you can find the source of inputStreamToString(final InputStream inputStream, final String charsetName)

Description

Read from an java.io.InputStream to a java.lang.String .

License

Open Source License

Parameter

Parameter Description
inputStream The java.io.InputStream
charsetName The encoding type used to convert bytes from the stream into characters to be scanned

Exception

Parameter Description
IOException If an IO exception has occurred

Return

The contents of the

Declaration

public static String inputStreamToString(final InputStream inputStream, final String charsetName)
        throws IOException 

Method Source Code


//package com.java2s;

import java.io.IOException;
import java.io.InputStream;

import java.nio.charset.Charset;

import java.util.Objects;
import java.util.Scanner;

public class Main {
    /**//from   ww w . j a v a 2s  .c  om
     * Read from an {@link java.io.InputStream} to a {@link java.lang.String}.
     * Closes the {@link java.io.InputStream} when done.
     *
     * @param inputStream The {@link java.io.InputStream}
     * @param charsetName The encoding type used to convert bytes from the
     *        stream into characters to be scanned
     * @return The contents of the {@link java.io.InputStream}
     * @throws IOException If an IO exception has occurred
     */
    public static String inputStreamToString(final InputStream inputStream, final String charsetName)
            throws IOException {
        final Scanner scanner = new Scanner(inputStream, charsetName).useDelimiter("\\A");
        String nextToken = "";
        if (scanner.hasNext()) {
            nextToken = scanner.next();
        }
        return nextToken;
    }

    /**
     * Read from an {@link java.io.InputStream} to a {@link java.lang.String}
     * using the default encoding. Closes the {@link java.io.InputStream} when done.
     *
     * @param inputStream The {@link java.io.InputStream}
     * @return The contents of the {@link java.io.InputStream}
     * @throws IOException If an IO exception has occurred
     */
    public static String inputStreamToString(final InputStream inputStream) throws IOException {
        Objects.requireNonNull(inputStream, "InputStream should be present");
        return inputStreamToString(inputStream, Charset.defaultCharset().name());
    }
}

Related

  1. getInputCharset()
  2. getStreamAsString(InputStream source, Charset charset)
  3. getText(InputStream stream, Charset charset)
  4. input2String(InputStream input, Charset encoding)
  5. inputStreamAsString(InputStream stream, Charset cs)
  6. inputstreamToString(InputStream input, CharsetDecoder decoder)
  7. inputStreamToString(InputStream inputStream, Charset charset)
  8. inputStreamToString(InputStream inputStream, String charset)
  9. inputStreamToString(InputStream is, Charset charset)