Java File Read via ByteBuffer readFull(Reader in)

Here you can find the source of readFull(Reader in)

Description

read Full

License

Apache License

Declaration

public static StringBuilder readFull(Reader in) throws IOException 

Method Source Code

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

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;
import java.io.Reader;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static StringBuilder readFull(Reader in) throws IOException {
        char buf[] = new char[4 * 1024];
        StringBuilder sb = new StringBuilder();

        for (;;) {
            int read = in.read(buf);

            if (read == -1) {
                break;
            }/*  w  w  w.  java 2  s.  c  o m*/

            sb.append(buf, 0, read);
        }

        return sb;
    }

    public static ByteBuffer read(File file, long offset, int length) throws IOException {
        FileChannel chan = channel(file, false);

        ByteBuffer buf = ByteBuffer.allocate(length);
        chan.position(offset);

        while (buf.remaining() > 0) {
            if (chan.read(buf) <= 0) {
                throw new IOException("Failed to read from channel.");
            }
        }

        buf.rewind();
        chan.close();

        return buf;
    }

    public static FileChannel channel(File file, boolean writeable) throws IOException {
        String opts = writeable ? "rw" : "r";
        RandomAccessFile fd = new RandomAccessFile(file, opts);
        FileChannel chan = fd.getChannel();

        return chan;
    }
}

Related

  1. ReadFloat(InputStream is)
  2. readFromBuffer(byte[] buffer, int start, int end)
  3. readFromFile(Path path)
  4. readFromFile(String fileName)
  5. readFromSocket(SocketChannel channel)
  6. readFully(final Reader input, final char[] buffer, final int offset, final int length)
  7. readFully(InputStream in)
  8. readFullyAndClose(InputStream input)
  9. readHeaderArea(InputStream in)