Java Text File Read by Charset readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)

Here you can find the source of readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)

Description

read Line From Stream

License

Open Source License

Declaration

public static String readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)
            throws IOException 

Method Source Code

//package com.java2s;
/*/*from   w  w w.  ja va  2s. c om*/
 * ====================================================================
 * Copyright (c) 2004-2010 TMate Software Ltd.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://svnkit.com/license.html
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 * ====================================================================
 */

import java.io.ByteArrayOutputStream;

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

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetDecoder;

public class Main {
    public static String readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder)
            throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int r = -1;
        while ((r = is.read()) != '\n') {
            if (r == -1) {
                String out = decode(decoder, byteBuffer.toByteArray());
                buffer.append(out);
                return null;
            }
            byteBuffer.write(r);

        }
        String out = decode(decoder, byteBuffer.toByteArray());
        buffer.append(out);
        return out;
    }

    private static String decode(CharsetDecoder decoder, byte[] in) {
        ByteBuffer inBuf = ByteBuffer.wrap(in);
        CharBuffer outBuf = CharBuffer.allocate(inBuf.capacity() * Math.round(decoder.maxCharsPerByte() + 0.5f));
        decoder.decode(inBuf, outBuf, true);
        decoder.flush(outBuf);
        decoder.reset();
        return outBuf.flip().toString();
    }
}

Related

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