Java File Read via ByteBuffer readFromSocket(SocketChannel channel)

Here you can find the source of readFromSocket(SocketChannel channel)

Description

read From Socket

License

Open Source License

Declaration

public static byte[] readFromSocket(SocketChannel channel) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Main {
    public static byte[] readFromSocket(SocketChannel channel) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(256);

        int bytes = 0;
        int totalBytes = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((bytes = channel.read(bb)) != -1) {
            totalBytes += bytes;//from   www . java 2  s  .  c  o  m
            if (totalBytes == 256 || !bb.hasRemaining()) {
                baos.write(bb.array(), 0, 256);
                bb.clear();
                totalBytes = 0;
            }
        }
        if (totalBytes > 0) {
            baos.write(bb.array(), 0, totalBytes);
        }

        return baos.toByteArray();
    }
}

Related

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