【问题标题】:How to read a binary file starting from a specific part如何从特定部分开始读取二进制文件
【发布时间】:2015-12-21 03:27:47
【问题描述】:

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

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

编辑:我忘了提到该文件将从另一个线程/活动/应用程序/设备访问。

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

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.

【问题讨论】:

  • 为什么不把标签位置放在文件末尾呢?
  • 如果您将标签位置放在文件末尾,比如说最后 8 个字节。然后您可以执行以下操作:读取最后 8 个字节 -> 获取标签的位置 -> 寻找位置 -> 读取标签和内容
  • @bladefury 它已经在文件末尾了。文件内容 -> 标签 -> 内容。我只是附加了新数据。无论如何,我认为您是说我也应该放置附加数据开始的位置,对吗?
  • 是的,在附加标签和内容后附加位置信息
  • @bladefury 听起来很合法。我试试看。

标签: java android string file-io binaryfiles


【解决方案1】:

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

用于附加数据:

    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
    }

【讨论】:

  • @PandaLion98 很难看出这如何解决您的问题,除非只有一个追加。
【解决方案2】:

只需 seek() 到你写标签的地方。

EDIT“你写标签的地方”由写之前的文件大小给出。

【讨论】:

  • 问题是偏移量是可变的。
  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • @PandaLion98 没关系,seek() 接受整数,可以是变量。
  • @EJP 变量因为没有固定值:)
  • @PandaLion9 所以你真正的问题是知道价值,而不是寻找?这不是它在你的问题中所说的。当然,您需要的值是在追加之前由文件大小给出的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-04
  • 2017-04-11
  • 1970-01-01
相关资源
最近更新 更多