Java Text File Read by Charset readInputStreamToString(InputStream instream, Charset charset)

Here you can find the source of readInputStreamToString(InputStream instream, Charset charset)

Description

Form a string from the contents of instream with charset charset .

License

Open Source License

Parameter

Parameter Description
instream to be read
charset is encoding of input stream's bytes

Exception

Parameter Description
IOException when reading fails

Return

String entire instream contents

Declaration

public static String readInputStreamToString(InputStream instream, Charset charset) throws IOException 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class Main {
    /**/*from w w  w  .j a  va2  s .c om*/
     * Form a string from the contents of {@code instream} with charset
     * {@code charset}.
     * @param instream to be read
     * @param charset is encoding of input stream's bytes
     * @return String entire instream contents
     * @throws IOException when reading fails
     */
    public static String readInputStreamToString(InputStream instream, Charset charset) throws IOException {
        return new String(readInputStreamToByteArray(instream), charset);
    }

    /**
     * Read the contents of {@code is} into a byte array.
     * @param instream to be read
     * @return byte[] entire instream bytes
     * @throws IOException when reading fails
     */
    public static byte[] readInputStreamToByteArray(InputStream instream) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        copyStream(instream, os);
        return os.toByteArray();
    }

    /**
     * Copy contents of {@code in} to {@code out}.
     * @param in is source of bytes
     * @param out is destination for bytes
     * @throws IOException if reading or writing fails
     */
    public static void copyStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
    }
}

Related

  1. readFileToList(String filePath, String charsetName)
  2. readFileToString(String filename, Charset encoding)
  3. readFileToString(String path, Charset charset)
  4. readFromInputStream(InputStream stream, Charset charset)
  5. readInputStream(InputStream stream, Charset cs)
  6. readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)
  7. readLines(InputStream in, Charset cs)
  8. readLines(InputStream input, Charset charset)
  9. readLines(InputStream is, CharsetDecoder decoder)