Java Convert via ByteBuffer toByteArray2(String filename)

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

Description

NIO way

License

Open Source License

Parameter

Parameter Description
filename a parameter

Exception

Parameter Description
IOException an exception

Declaration

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

Method Source Code


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

import java.nio.channels.FileChannel;

public class Main {
    /**//ww w  .  j  a  v a2  s  .  c  o m
     * NIO way
     *
     * @param filename
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray2(String filename) throws IOException {

        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }

        FileChannel channel = null;
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(f);
            channel = fs.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while ((channel.read(byteBuffer)) > 0) {
                // do nothing
                // System.out.println("reading");
            }
            return byteBuffer.array();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

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