Java Convert via ByteBuffer toByteArray3(String filename)

Here you can find the source of toByteArray3(String filename)

Description

to Byte Array

License

Open Source License

Declaration

public static byte[] toByteArray3(String filename) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {

    public static byte[] toByteArray3(String filename) throws IOException {

        FileChannel fc = null;/*  ww w . j  ava2s  . co m*/
        try {
            fc = new RandomAccessFile(filename, "r").getChannel();
            MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).load();
            System.out.println(byteBuffer.isLoaded());
            byte[] result = new byte[(int) fc.size()];
            if (byteBuffer.remaining() > 0) {
                // System.out.println("remain");
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                fc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. toByteArray(String bits)
  2. ToByteArray(String hexString)
  3. toByteArray(String value)
  4. toByteArray(UUID uniqueId)
  5. toByteArray2(String filename)
  6. toByteArrayFromInt(int intValue, boolean shortSize)
  7. toByteArrayFromLong(long longValue)
  8. toBytes(BigDecimal number, int byteLength)
  9. toBytes(char[] ch)