Java Text File Read by Charset readToString(InputStream in, Charset charset)

Here you can find the source of readToString(InputStream in, Charset charset)

Description

Read the input stream into a string

License

Open Source License

Parameter

Parameter Description
in the stream
charset the charset to be used

Return

the string

Declaration

public static String readToString(InputStream in, Charset charset) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2016 BestSolution.at and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from ww  w.  ja  va 2 s .  c  om*/
 *     Tom Schindl<tom.schindl@bestsolution.at> - initial API and implementation
 *******************************************************************************/

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.nio.charset.Charset;

public class Main {
    /**
     * Read the input stream into a string
     *
     * @param in
     *            the stream
     * @param charset
     *            the charset to be used
     * @return the string
     */
    public static String readToString(InputStream in, Charset charset) {
        return readToString(in, 1024, charset);
    }

    /**
     * Read the input stream into a string
     *
     * @param in
     *            the stream
     * @param bufferLength
     *            the buffer length
     * @param charset
     *            the charset
     * @return the string
     */
    public static String readToString(InputStream in, int bufferLength, Charset charset) {
        StringBuilder b = new StringBuilder();
        char[] buf = new char[bufferLength];
        InputStreamReader r = new InputStreamReader(in, charset);
        int l;
        try {
            while ((l = r.read(buf, 0, bufferLength)) != -1) {
                b.append(buf, 0, l);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return b.toString();
    }
}

Related

  1. readString(InputStream in, String charset)
  2. readStringFromStream(InputStream stream, Charset charset)
  3. readTextFile(final String fileNamePath, final String charsetName)
  4. readTextStream(InputStream is, Charset charset)
  5. readToBuffer(StringBuffer buffer, String filePath, Charset charset)
  6. readToString(ReadableByteChannel in, Charset charset)
  7. readURL(URL url, Charset encoding)
  8. readWholeFile(String filename, String charSet)