Java Text File Read by Charset readStreamAsString(final InputStream iStream, Charset iCharset)

Here you can find the source of readStreamAsString(final InputStream iStream, Charset iCharset)

Description

read Stream As String

License

Apache License

Declaration

public static String readStreamAsString(final InputStream iStream,
            Charset iCharset) throws IOException 

Method Source Code

//package com.java2s;
/*//w w  w.  j  a va  2  s .co m
 *
 *  *  Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
 *  *
 *  *  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.
 *  *
 *  * For more information: http://www.orientechnologies.com
 *
 */

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    public static final String UTF8_BOM = "\uFEFF";

    public static String readStreamAsString(final InputStream iStream)
            throws IOException {
        return readStreamAsString(iStream, StandardCharsets.UTF_8);
    }

    public static String readStreamAsString(final InputStream iStream,
            Charset iCharset) throws IOException {
        final StringBuffer fileData = new StringBuffer(1000);
        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(iStream, iCharset));
        try {
            final char[] buf = new char[1024];
            int numRead = 0;

            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);

                if (fileData.length() == 0 && readData.startsWith(UTF8_BOM))
                    // SKIP UTF-8 BOM IF ANY
                    readData = readData.substring(1);

                fileData.append(readData);
            }
        } finally {
            reader.close();
        }
        return fileData.toString();

    }
}

Related

  1. readLines(InputStream input, Charset charset)
  2. readLines(InputStream is, CharsetDecoder decoder)
  3. readLines(String filePath, Charset charset)
  4. readLines(String path, Charset charset)
  5. readNextWord(BufferedInputStream in, Charset cs)
  6. readStreamToString(InputStream stream, Charset encoding)
  7. readString(DataInput input, int length, Charset charset)
  8. readString(final InputStream in, final Charset charset)
  9. readString(final InputStream in, final Charset charset)