Android InputStream to String Convert getString(InputStream is)

Here you can find the source of getString(InputStream is)

Description

Get string from an InputStream object

Parameter

Parameter Description
is a parameter

Exception

Parameter Description

Return

null if fail

Declaration

public static String getString(InputStream is) throws IOException,
        NullPointerException 

Method Source Code

//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Main {
    /** Buffer size for InputStream */
    private static final int BUFF_SIZE = 2048;

    /**/*  w  w  w  . j  a v  a 2  s.  c  o m*/
     * Get string from an InputStream object
     * @param is
     * @return null if fail
     * @throws java.io.IOException problem with the InputStream object
     * @throws java.lang.NullPointerException null InputStream
     */
    public static String getString(InputStream is) throws IOException,
            NullPointerException {
        if (is == null)
            throw new NullPointerException("null InputStream object");

        char[] buf = new char[BUFF_SIZE];

        Reader r = new InputStreamReader(is, "UTF-8");
        StringBuilder s = new StringBuilder();

        while (true) {
            int n = r.read(buf);
            if (n < 0)
                break;
            s.append(buf, 0, n);
        }

        return s.toString();
    }

    /**
     * Get string from file
     * @param file a text file
     * @return string which contains content of the text file
     */
    public static String getString(File file) throws IOException {
        if (file == null)
            throw new NullPointerException("null file");

        StringBuilder sb = new StringBuilder();

        BufferedReader br = new BufferedReader(new FileReader(file));
        String line;

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }

        return sb.toString();
    }
}

Related

  1. convertInputStreamToString(InputStream inputStream)
  2. inputStream2String(InputStream is)
  3. readStreamAsString(InputStream is)
  4. readStringFromStream(InputStream is)
  5. inputStream2String(InputStream is)
  6. inputStream2String(InputStream in)
  7. stream2String(InputStream is, int maxLength)
  8. fromStream(InputStream stream)