Java InputStreamReader Read All readAll(InputStream input)

Here you can find the source of readAll(InputStream input)

Description

read All

License

LGPL

Declaration

public static String readAll(InputStream input) throws IOException 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {
    public static void readAll(Reader reader, Writer writer) throws IOException {
        char buffer[] = new char[1024];
        int count = 0;

        do {//from  w w  w .  j a v a 2  s . c  o  m
            count = reader.read(buffer);
            if (count > 0) {
                writer.write(buffer, 0, count);
            }
        } while (count > 0);
    }

    public static void readAll(InputStream input, Writer writer) throws IOException {
        Reader reader = new InputStreamReader(input);

        try {
            readAll(reader, writer);
        } finally {
            closeSilently(reader);
        }
    }

    public static String readAll(InputStream input) throws IOException {
        StringWriter writer = new StringWriter();
        readAll(input, writer);
        return writer.getBuffer().toString();
    }

    public static void closeSilently(Object obj, Closeable stream) {
        if (stream == null) {
            return;
        }
        try {
            stream.close();
        } catch (IOException e) {
            Logger.getLogger(obj.getClass().getName()).log(Level.WARNING, "Error occured while closing a stream.",
                    e);
        }
    }

    public static void closeSilently(Closeable stream) {
        if (stream == null) {
            return;
        }
        try {
            stream.close();
        } catch (IOException e) {
            Logger.getLogger("Utils").log(Level.WARNING, "Error occured while closing a stream.", e);
        }
    }
}

Related

  1. readAll(File file)
  2. readAll(InputStreamReader reader)
  3. readAll(Reader source)