Java Text File Read by Charset readFile(final InputStream is, final Charset encoding)

Here you can find the source of readFile(final InputStream is, final Charset encoding)

Description

Reads a file.

License

Apache License

Parameter

Parameter Description
is InputStream for the file
encoding encoding for the file

Exception

Parameter Description
IOException an exception

Return

the String retpresentation of the file

Declaration

public static String readFile(final InputStream is, final Charset encoding) throws IOException 

Method Source Code


//package com.java2s;
/*//from ww w  .  j  av  a  2  s  . c om
 * Copyright 2015 ANTONIO CARLON
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

public class Main {
    /**
     * Reads a file.
     *
     * @param is
     *            InputStream for the file
     * @param encoding
     *            encoding for the file
     * @return the String retpresentation of the file
     * @throws IOException
     */
    public static String readFile(final InputStream is, final Charset encoding) throws IOException {
        if (is == null) {
            throw new IllegalArgumentException("The InputStream is null");
        }
        if (encoding == null) {
            throw new IllegalArgumentException("The Charset is null");
        }

        final Reader reader = new BufferedReader(new InputStreamReader(is, encoding));
        final StringBuilder builder = new StringBuilder();
        final char[] buffer = new char[8192];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        return builder.toString();
    }
}

Related

  1. readFile(File file, Charset charset)
  2. readFile(File file, Charset charset)
  3. readFile(File file, Charset cs)
  4. readFile(File file, String charsetName)
  5. readFile(File theFile, Charset theCharset)
  6. readFile(String path, Charset charset)
  7. readFile(String path, Charset encoding)
  8. readFileAsString(String path, String charsetName)
  9. readFileContents(File file, Charset charset)