Java File Read via ByteBuffer readFile(java.io.File file)

Here you can find the source of readFile(java.io.File file)

Description

read File

License

Open Source License

Declaration

@SuppressWarnings({ "UnusedDeclaration" })
    private static java.nio.ByteBuffer readFile(java.io.File file)
            throws java.io.IOException 

Method Source Code

//package com.java2s;

public class Main {
    private static final int PAGE_SIZE = 4096;

    @SuppressWarnings({ "UnusedDeclaration" })
    private static java.nio.ByteBuffer readFile(java.io.File file)
            throws java.io.IOException {
        java.io.FileInputStream fis = new java.io.FileInputStream(file);
        java.nio.ByteBuffer buffer = java.nio.ByteBuffer
                .allocate(PAGE_SIZE);//from   ww w  .jav  a  2 s.  co  m
        java.nio.channels.ReadableByteChannel channel = java.nio.channels.Channels
                .newChannel(fis);

        int count = 0;
        while (count >= 0) {
            count = channel.read(buffer);
            if (count > 0 && !buffer.hasRemaining()) {
                java.nio.ByteBuffer biggerBuffer = java.nio.ByteBuffer
                        .allocate(buffer.limit() + PAGE_SIZE);
                biggerBuffer.put((java.nio.ByteBuffer) buffer.rewind());
                buffer = biggerBuffer;
            }
        }

        if (buffer != null)
            buffer.flip();

        return buffer;
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(String filename)
  7. readFile(String filename)
  8. readFile(String fileName)
  9. readFile(String filename)