3

我想将原始数据块保存到文件中,然后一一读取这些块。除了以下疑问之外,这没什么大不了的:

使用什么确切字节作为分隔符,即识别一个块的结尾和下一个块的开始?鉴于块数据也可能随机包含这样的字节序列。

注意:块的大小可变并且包含随机数据。它们jpeg实际上是图像。

4

2 回答 2

3

您可以首先将块的长度作为固定大小的值写入文件,例如 4 字节整数,然后是数据本身:

public void appendChunk(byte[] data, File file) throws IOException {
    DataOutputStream stream = null;
    try {
        stream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file, true)));
        stream.writeInt(data.length);
        stream.write(data);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

如果您以后必须从该文件中读取块,则首先读取第一个块的长度。您现在可以决定是否读取块数据,或者是否跳过它并继续下一个块。

public void processChunks(File file) throws IOException {
    DataInputStream stream = null;
    try {
        stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        while (true) {
            try {
                int length = stream.readInt();
                byte[] data = new byte[length];
                stream.readFully(data);
                // todo: do something with the data
            } catch (EOFException e) {
                // end of file reached
                break;
            }
        }
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

您还可以添加有关块的其他元数据,例如使用 stream.writeUTF(...) 写入文件的原始名称。您只需确保以相同的顺序写入和读取相同的数据。

于 2012-11-21T20:16:59.223 回答
1

创建第二个文件,在其中将块的字节范围保存在块文件中,或将该信息添加到块文件的标题中。做过一次类似的事情,不要忘记字节范围比标题长度的额外偏移量。

int startbyte = 0;
int lastByte = 0;
int chunkcount = 0;
File chunkfile;
File structurefile;
for (every chunk) {
    append chunk to chunkfile
    lastByte = startByte + chunk.sizeInBytes()
    append to structurefile: chunkcount startByte lastByte
    chunkcount++;
    startByte = lastByte + 1
}
于 2012-11-21T19:52:09.857 回答