Search code examples
javabytearraysrandomaccessfile

How to convert bytes into a byte array?


So I implemented a Bytebuffer and I want to store the bytes I get into a Byte array, but I can't seem to find a simple solution online. Any suggestions would be appreciated!

Here's the code

public AbstractBlock readBlock(int blockNum, AbstractDBFile f)
            throws IOException {

        f.setCurBlockPos(blockNum);

        Block block = new Block();
        byte[] data = new byte[4096];
        String filename = f.getFileName();
        File ourFile = new File(filename);
        RandomAccessFile file = new RandomAccessFile(ourFile, "r");
        FileChannel inChannel = file.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(4096);
        inChannel.read(bb);
        while(inChannel.read(bb)>0){
        bb.flip();
        for (int i =0; i<bb.limit(); i++){
            System.out.println((char)bb.get()); 
//I want to insert what is printed into the byte Array data
        }
    //  bb.clear();
    }
        inChannel.close();
        file.close();
        block.setData(data);
        return block;
    }

Solution

  • Java 7 offers Files.readAllBytes(Path).

    Usage:

    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.Path;
    
    Path fp = Paths.get("file_path");
    byte[] data = Files.readAllBytes(fp);