gpt4 book ai didi

Java输入输出二进制文件字节大小转换后不匹配

转载 作者:行者123 更新时间:2023-12-02 05:25:17 25 4
gpt4 key购买 nike

我的输入数据集是二进制格式的 16 位整数(2 字节)的 1201x1201 个元素。文件总大小为 2884802 字节。我使用 ByteBuffer 将这些数据读入 Java,然后使用 ObjectOutputStream 的 writeShort() 方法将其写为无符号短整型的二维数组。现在我的文件大小是 2898893 字节。为什么会出现这种差异?

    FileChannel fileInputChannel = new FileInputStream(fileInput).getChannel();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileOutput));
short[][] data = new short[1201][1201];
ByteBuffer bb = ByteBuffer.allocateDirect(2884802);
while (bb.remaining() > 0)
fileInputChannel.read(bb);
fileInputChannel.close();
bb.flip();
ShortBuffer sb=null;
if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN))
{
sb = bb.order(ByteOrder.BIG_ENDIAN).asShortBuffer();
}
else
{
sb = bb.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
}
for (int i=0;i<1201;i++)
{
for (int j=0;j<1201;j++)
{

data[i][j] = sb.get();
oos.writeShort(data[i][j] & 0xFFFF);
}
}

最佳答案

不要使用DataOutputStream,这意味着要在序列化中使用。使用您已有的FileOutputStream,如下所示:

    FileChannel fileInputChannel = new FileInputStream(fileInput).getChannel();
FileOutputStream fos = new FileOutputStream(fileOutput);
short[][] data = new short[1201][1201];
ByteBuffer bb = ByteBuffer.allocateDirect(2884802);
while (bb.remaining() > 0)
fileInputChannel.read(bb);
fileInputChannel.close();
bb.flip();
ShortBuffer sb=null;
if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN))
{
for (int i=0;i<1201;i++)
{
for (int j=0;j<1201;j++)
{
fos.write((data[i][j] >> 8) & 0xFF);
fos.write(data[i][j] & 0xFF);
}
}
}
else
{
for (int i=0;i<1201;i++)
{
for (int j=0;j<1201;j++)
{
fos.write(data[i][j] & 0xFF);
fos.write((data[i][j] >> 8) & 0xFF);
}
}
}

关于Java输入输出二进制文件字节大小转换后不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26098541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com