如何将字节转换为字节数组?

时间:2016-03-18 02:15:03

标签: java byte bytearray randomaccessfile

所以我实现了一个Bytebuffer并且我希望将我得到的字节存储到Byte数组中,但我似乎无法在线找到一个简单的解决方案。任何建议将不胜感激!

这是代码

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;
    }

1 个答案:

答案 0 :(得分:0)

Java 7提供Files.readAllBytes(Path)。

用法:

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);