【问题标题】:How to start reading a file at specific position?如何在特定位置开始读取文件?
【发布时间】:2014-01-04 21:36:02
【问题描述】:

首先我有几个小时的 Java 经验,所以如果问题有点简单,抱歉。

现在,我想读取一个文件,但我不想从文件开头开始,而是想跳过前 1024 个字节然后开始读取。有没有办法做到这一点 ?我意识到 RandomAccessFile 可能有用,但我不确定。

try {
     FileInputStream inputStream=new FileInputStream(fName);
       // skip 1024 bytes somehow and start reading .
} catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
}

【问题讨论】:

  • 你可以只读取 1024 个字节然后做你的事情。
  • @SotiriosDelimanolis 是的,这是一种处理方式,但它不是一种没用的吗?
  • @SotiriosDelimanolis btw 在 1024 字节之后,有时我需要跳过部分文件,所以如果我学会这样做会更好
  • 相关:如果是二进制文件:stackoverflow.com/questions/3624352/…;如果是文本文件:stackoverflow.com/questions/10102703/…

标签: java file file-io io


【解决方案1】:

您将需要使用FileInputStream.skip 方法来寻找您想要的点,然后从该点开始阅读。 javadocs 中有更多关于FileInputStream 的信息,您可能会感兴趣。

【讨论】:

  • @dcolish 顺便说一下我的文件是二进制文件。它会导致任何问题吗?
  • @TheGost: 一点也不:“FileInputStream 用于读取原始字节流,例如图像数据。”
【解决方案2】:

您可以在这里使用类似 skipBytes() 的方法

/**
 * Read count bytes from the InputStream to "/dev/null".
 * Return true if count bytes read, false otherwise.
 * 
 * @param is
 *          The InputStream to read.
 * @param count
 *          The count of bytes to drop.
 */
private static boolean skipBytes(
    java.io.InputStream is, int count) {
  byte[] buff = new byte[count];
  /*
   * offset could be used in "is.read" as the second arg
   */
  try {
    int r = is.read(buff, 0, count);
    return r == count;
  } catch (IOException e) {
    e.printStackTrace();
  }
  return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多