Java File Read via ByteBuffer readToByteArray(String fname)

Here you can find the source of readToByteArray(String fname)

Description

read a file into a byte array.

License

Open Source License

Parameter

Parameter Description
fname the file name

Exception

Parameter Description
IOException in case of error.

Return

byte[] a byte array with file contents.

Declaration

public static byte[] readToByteArray(String fname) throws IOException 

Method Source Code


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

public class Main {
    /**/*from w  w  w.j  ava 2  s .  c  om*/
     * read a file into a byte array.
     * @param fname the file name
     * @return byte[] a byte array with file contents.
     * @throws IOException in case of error.
     */
    public static byte[] readToByteArray(String fname) throws IOException {
        File f = new File(fname);
        long l = f.length();
        FileInputStream fs = new FileInputStream(fname);
        FileChannel fc = fs.getChannel();
        ByteBuffer dst = ByteBuffer.allocate((int) l);
        fc.read(dst);
        byte b[] = dst.array();
        fc.close();
        fs.close();
        return (b);
    }
}

Related

  1. readString(ReadableByteChannel channel)
  2. readStringFromFile(String path)
  3. readStringFromSocketChannel(SocketChannel sc)
  4. readStringInUTF8(DataInput in)
  5. readToBuffer(final String filename)
  6. readTwoByteInt(byte[] array, int start)
  7. readTxtFromFile(File file)
  8. readUint32(final DataInput di)
  9. readUint32AsInt(DataInput di)