使用Java在文件中写入和读取多个byte []

Pit*_*ith 4 java bytearray file

我必须在文件中写字节数组.我不能一次做到这一点所以我不能把我的数组放在一个容器中.我的数组的大小也是可变的.其次,文件非常庞大,所以我必须拆分它,以便按数组读取它.

我怎样才能做到这一点 ?我试图逐行写我的字节数组,但我还没能.如何在我的数组之间放置一个分隔符并将其拆分为此分隔符?

编辑:

我试过这个:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(byteArray);
Run Code Online (Sandbox Code Playgroud)

但是,我多次执行此代码,因此ObjectOutputStream每次添加一个损坏文件的新标头.

我也尝试:

out.write(byteArray);
Run Code Online (Sandbox Code Playgroud)

但我无法分离我的阵列.所以我试图附加一个'\n',但没有用.我在寻找像FileUtils这样的库,以便逐行写byte [],但我没有找到.

Ami*_*nde 7

您可以使用现有的集合,例如List来维护byte []的List并将其传输

    List<byte[]> list = new ArrayList<byte[]>();
    list.add("HI".getBytes());
    list.add("BYE".getBytes());

    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
            "test.txt"));
    out.writeObject(list);

    ObjectInputStream in = new ObjectInputStream(new FileInputStream(
            "test.txt"));
    List<byte[]> byteList = (List<byte[]>) in.readObject();

    //if you want to add to list you will need to add to byteList and write it again
    for (byte[] bytes : byteList) {
        System.out.println(new String(bytes));
    }
Run Code Online (Sandbox Code Playgroud)

输出:

   HI
   BYE
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用RandomAccessFile.这不会强迫您阅读完整文件,您可以跳过您不想阅读的数据.

     DataOutputStream dataOutStream = new DataOutputStream(
            new FileOutputStream("test1"));
    int numberOfChunks = 2;
    dataOutStream.writeInt(numberOfChunks);// Write number of chunks first
    byte[] firstChunk = "HI".getBytes();
    dataOutStream.writeInt(firstChunk.length);//Write length of array a small custom protocol
    dataOutStream.write(firstChunk);//Write byte array

    byte[] secondChunk = "BYE".getBytes();
    dataOutStream.writeInt(secondChunk.length);//Write length of array
    dataOutStream.write(secondChunk);//Write byte array

    RandomAccessFile randomAccessFile = new RandomAccessFile("test1", "r");
    int chunksRead = randomAccessFile.readInt();
    for (int i = 0; i < chunksRead; i++) {
        int size = randomAccessFile.readInt();
        if (i == 1)// means we only want to read last chunk
        {
            byte[] bytes = new byte[size];
            randomAccessFile.read(bytes, 0, bytes.length);
            System.out.println(new String(bytes));
        }
        randomAccessFile.seek(4+(i+1)*size+4*(i+1));//From start so 4 int + i* size+ 4* i ie. size of i
    }
Run Code Online (Sandbox Code Playgroud)

输出:

BYE
Run Code Online (Sandbox Code Playgroud)