Java Convert via ByteBuffer toString(Reader reader)

Here you can find the source of toString(Reader reader)

Description

to String

License

Apache License

Declaration

public static String toString(Reader reader) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;

import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    public static String toString(Reader reader) throws IOException {
        StringWriter sw = new StringWriter();
        copyStream(reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader),
                new BufferedWriter(sw));
        return sw.toString();
    }//from  w ww. j a  va 2  s  .co  m

    public static void copyStream(BufferedReader reader, BufferedWriter writer) throws IOException {
        String line = null;
        while ((line = reader.readLine()) != null) {
            writer.write(line);
        }
        writer.flush();
    }

    public static void copyStream(final ReadableByteChannel src, final WritableByteChannel dest)
            throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

        while (src.read(buffer) != -1) {
            buffer.flip();
            dest.write(buffer);
            buffer.compact();
        }

        buffer.flip();

        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }

    public static void copyStream(InputStream in, OutputStream out) throws IOException {
        final ReadableByteChannel inputChannel = Channels.newChannel(in);
        final WritableByteChannel outputChannel = Channels.newChannel(out);
        copyStream(inputChannel, outputChannel);
    }
}

Related

  1. toString(final String filename)
  2. toString(final Xid xid)
  3. toString(InputStream is)
  4. toString(Object o)
  5. toString(Reader r)
  6. toText(@Nonnull byte[] bytes)
  7. toThriftBinary(UUID uuid)
  8. toURI(String value)
  9. toUTF(byte[] bytes)