【问题标题】:Does Java save the read position in the InputStream?Java 是否将读取位置保存在 InputStream 中?
【发布时间】:2011-05-04 10:23:46
【问题描述】:

我正在读取数据,Java 是“保存”你读取的字节,还是我必须使用偏移量?

【问题讨论】:

  • 哦,来一个!发布最后一个问题后,您可以阅读文档并尝试一下。您会很快看到,在阅读了一些数据后,该位置得到了提升。也许你会想检查the I/O tutorial

标签: java byte offset


【解决方案1】:

FileInputStream 确实可以保存您的位置。

如果你有一个 3 字节的文件,0xff 0x00 0x0c,调用:

System.out.println(fis.read());
System.out.println(fis.read());
System.out.println(fis.read());

将输出:

255
0
12

【讨论】:

    【解决方案2】:

    你只是为了反映@WhiteFang的写作解决方案。

    FileInputStream fis = new FileInputStream(files[0]);
    DataInputStream dis = new DataInputStream(new BufferedInputStream(fis));
    int numFiles = dis.readInt();
    int numBytesInName = dis.readInt();
    String filename = dis.readUTF();
    long numBytesInFile = dis.readLong();
    // loop to read bytes into a byte[]
    

    顺便说一句,使用 writeUTF/readUTF 会使写入文件名的长度变得多余。此外,如果您不打算在此信息之后写任何内容,则无需记录文件数。

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 2021-07-02
      • 2010-10-22
      • 2011-09-03
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 2016-04-29
      相关资源
      最近更新 更多