如何从特定部分开始读取二进制文件

How to read a binary file starting from a specific part

我在我的代码中所做的只是使用 FileOutputStream 的追加标志将一个标记然后一些字符串数据追加到一个二进制文件中。现在,我如何从指定的标签开始阅读?我不知道从哪里开始。

文件和字符串的大小是可变的,所以我真的不能相信它。唯一不变的是标签。

编辑: 我忘了提到该文件将从另一个 thread/activity/app/device.

访问

用于附加一些数据的代码:

String TAG = "CLIPPYDATA-";
String content = "The quick brown fox jumps over the lazy dog."; //size not fixed, sample purpose only.

FileOutputStream output = new FileOutputStream("/path/to/file", true);
try {
        output.write((TAG + content).getBytes());
} finally {
        //output.flush(); (should I?)
        output.close();
}

示例输出:

yyvAžîéÃI&8QÀ Ø +ZŠ( ¢Š( ¢Š(ÿÙCLIPPYDATA-The quick brown fox jumps over the lazy dog.

示例输入:

yyvAžîéÃI&8QÀ Ø +ZŠ( ¢Š( ¢Š(ÿÙCLIPPYDATA-The quick brown fox jumps over the lazy dog.

期望的输出:

CLIPPYDATA-The quick brown fox jumps over the lazy dog.

只需 seek() 到您编写标签的位置。

EDIT 'Where you wrote the tag' 由写入前的文件大小给出。

正如评论中所讨论的,这里有一个例子:

附加数据:

    String TAG = "CLIPPYDATA-";
    String content = "The quick brown fox jumps over the lazy dog."; //size not fixed, sample purpose only.
    File outputFile  = new File("/path/to/file");
    long fileLength = outputFile.length();
    FileOutputStream output = new FileOutputStream(outputFile, true);
    try {
        output.write((TAG + content).getBytes());
        byte[] bytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(fileLength).array();
        output.write(bytes);
    } finally {
        //output.flush(); (should I?)
        output.close();
    }

读取数据:

    RandomAccessFile raf = new RandomAccessFile("/path/to/file", "rb");
    long endPositon = raf.length() - Long.SIZE / Byte.SIZE;
    // get last 8 bytes
    raf.seek(endPositon);
    long tagPosition = raf.readLong();
    raf.seek(tagPosition);
    byte[] bytes = new byte[endPositon - tagPosition];
    raf.read(bytes);
    String appendedData = new String(bytes);
    if (appendedData.startsWith(TAG)) {
        // appendedData is what you want
    }