Java File Read via ByteBuffer getStringContents(ReadableByteChannel channel)

Here you can find the source of getStringContents(ReadableByteChannel channel)

Description

Gets String contents from channel and closes it.

License

Apache License

Declaration

public static String getStringContents(ReadableByteChannel channel) throws IOException 

Method Source Code


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

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ReadableByteChannel;

import java.nio.charset.StandardCharsets;

public class Main {
    /** Gets String contents from channel and closes it. */
    public static String getStringContents(ReadableByteChannel channel) throws IOException {
        // TODO Checks if a supplier would be nice
        try {//from   w ww .jav a2 s  .com
            ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
            StringBuilder sb = new StringBuilder();
            int bytesRead = channel.read(buffer);
            while (bytesRead != -1) {
                buffer.flip();
                CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer);
                sb.append(charBuffer.toString());
                buffer.clear();
                bytesRead = channel.read(buffer);
            }
            return sb.toString();
        } finally {
            channel.close();
        }
    }
}

Related

  1. copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)
  2. copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
  3. copyStream(BufferedReader reader, BufferedWriter writer)
  4. count(final ReadableByteChannel src)
  5. getReadBuffer(File file)
  6. largeFileReader(String filename)
  7. mapReadWrite(File file)
  8. nioCopy(ReadableByteChannel input, WritableByteChannel output)
  9. openReadOnly(Path path, int offset, int length)