Java InputStream to String getStreamContents(final InputStream is)

Here you can find the source of getStreamContents(final InputStream is)

Description

get Stream Contents

License

Open Source License

Declaration

public static String getStreamContents(final InputStream is) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.InputStream;

import java.util.NoSuchElementException;

import java.util.Scanner;

public class Main {
    private static final String DEFAULT_ENCODING = "UTF-8";

    public static String getStreamContents(final InputStream is) throws IllegalArgumentException {
        return getStreamContents(is, DEFAULT_ENCODING);
    }/* w  ww  .j  av  a  2  s  .  c  om*/

    public static String getStreamContents(final InputStream is, final String enc) throws IllegalArgumentException {
        String content;
        try (Scanner scanner = new Scanner(is, enc).useDelimiter("\\Z")) {
            content = getScannerContents(scanner);
        } catch (NoSuchElementException | IllegalStateException e) {
            throw e;
        }
        return content;
    }

    public static String getScannerContents(final Scanner scanner) throws IllegalArgumentException {
        String content;
        if (scanner.hasNext()) { // will be false if file size == 0
            content = scanner.next();
        } else {
            content = "";
        }
        return content;
    }
}

Related

  1. getStreamAsString(InputStream stream, String charset)
  2. getStreamContent(InputStream is)
  3. getStreamContent(InputStream stream, int bufferSize)
  4. getStreamContentAsString(InputStream is)
  5. getStreamContentAsString(InputStream is, String encoding)
  6. inputStream2String(InputStream in)
  7. inputStream2String(InputStream in)
  8. inputStream2String(InputStream in)
  9. InputStream2String(InputStream in, String encoding)