【问题标题】:Java FileInput/OutputStream and ByteBufferJava FileInput/OutputStream 和 ByteBuffer
【发布时间】:2015-12-13 20:29:03
【问题描述】:

如何使用 ByteBuffer 将整数 1432 写入 FileOutputStream 写入的文件中。由于 1432 占用超过一个字节,我们不能使用 write() 方法。 再者,后面使用 FileInputStream read() 方法时如何取回整数呢?

我尝试使用:

int i = 1432;
byte[] bytesi = ByteBuffer.allocate(4).putInt(i).array();
fileOS.write(bytesi);

但是当读取文件时:

int e = fileIS.read();
System.out.println(e);
int e1 = fileIS.read();
System.out.println(e1);
int e2 = fileIS.read();
System.out.println(e2);
int e3 = fileIS.read();
System.out.println(e3);

我得到如下输出:

255
132
201
255

【问题讨论】:

  • @jonasnas 那么将存储多少字节?如果我使用 fileOS.write(i)
  • 好的,明白你的意思。你的意思是你不能直接使用它

标签: java fileinputstream fileoutputstream bytebuffer


【解决方案1】:

由于您使用 ByteBuffer 从整数生成字节,因此您也可以使用它进行逆变换

byte[] bytes = new byte[4];
fis.read(bytes);
int x = ByteBuffer.wrap(bytes).getInt();

【讨论】:

    【解决方案2】:

    XY 问题。您不需要 ByteBuffer, 您需要将 int 写入二进制文件。 DataOutputStream 拥有您需要的所有方法,并且已经可以与 FileOutputStream. 一起使用,同样DataInputStream 已经可以与 FileInputStream. 一起使用

    【讨论】:

      【解决方案3】:

      您可以将 FileInputStreamFileOutputStream 包装到 DataInputStream / DataOutputStream 中,以获得各种数据类型的辅助方法,例如 readInt / writeInt

      http://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html

      使用示例:http://www.tutorialspoint.com/java/io/dataoutputstream_writeint.htm

      【讨论】:

        【解决方案4】:

        与上面相同的基本答案,使用 ByteBuffer 函数,但不要乱用你自己的 byte[]。

        ByteBuffer bytesIn = ByteBuffer.allocate(4);
        fileIS.read(bytesIn.array());
        int e = bytesIn.getInt();
        

        您也可以/应该这样做以写入字节,例如

        int i = 1432;
        ByteBuffer bytesOut = ByteBuffer.allocate(4).putInt(test);
        outFile.write(bytesOut.array());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-27
          • 1970-01-01
          • 2010-10-09
          • 2011-02-12
          • 1970-01-01
          • 2014-03-30
          • 1970-01-01
          • 2015-07-21
          相关资源
          最近更新 更多