为了账号安全,请及时绑定邮箱和手机立即绑定

字节从文件中读取错误?

字节从文件中读取错误?

泛舟湖上清波郎朗 2022-11-30 17:00:52
所以,我试图将 3 个 long 存储到一个文件中,但它会包含大量数据,因此我将它们转换为字节数组并保存。我目前保存它们的方法:try (FileOutputStream output = new FileOutputStream(path, true)) {                    //Put the data into my format                    byte[] data = new byte[24];                    main.getLogger().log(Level.INFO, "Saving most sig bits");                    System.arraycopy(ByteUtils.longToBytes(uuid.getMostSignificantBits()), 0, data, 0, 8);                    System.arraycopy(ByteUtils.longToBytes(uuid.getLeastSignificantBits()), 0, data, 8, 8);                    System.arraycopy(ByteUtils.longToBytes(player.getTokens()), 0, data, 16, 8);                    //Write data in the format                    output.write(data);                }longToBytes 方法:private static ByteBuffer buffer = ByteBuffer.allocate(8);public static byte[] longToBytes(long x) {    System.out.println(x);    buffer.putLong(0, x);    return buffer.array();}字节数组保存到文件中,但第一个字节被截断。longToByes 中的 print 语句打印 8 三次。原始多头是:-9089798603852198353, -5339652910133477779, 5992如果我打印字节数组,我得到:-127, -38, -116, 84, 97, -116, 78, 47, -75, -27, -67, -8, 11, -100, -2, 109, 0, 0, 0, 0, 0、0、23、104(24 字节)但是在文件中我看到:ÚŒTaŒN/µå½ø(VT symbol)œþm(nul)(nul)(nul)(nul)(nul)(nul)(etb)h 是 23 个字节(第一个框没有显示在记事本++)但如果我用bytes = IOUtils.toByteArray(new FileReader(file));我懂了:64, -38, -116, 84, 97, -116, 78, 47, -75, -27, -67, -8, 11, -100, -2, 109, 0, 0, 0, 0, 0 , 0, 23, 104(24 字节)-127 以某种方式替换为 64。我用“”连接字节以顺便打印它。
查看完整描述

1 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

不要用于FileReader从文件中读取原始字节。改用FileInputStream。


的问题FileReader是它通过尝试使用某种字符编码(如果没有给出则使用默认编码)来解码字节,从而从文件中读取chars,而不是。bytes


bytes = IOUtils.toByteArray(new FileInputStream(file));

或者,您可以使用DataOutputStreamlong 直接写入输出流并使用DataInputStream从输入流读取。


try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {

    out.writeLong(uuid.getMostSignificantBits());

    out.writeLong(uuid.getLeastSignificantBits());

    out.writeLong(player.getTokens());

}


try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {

    long uuidMSB = in.readLong();

    long uuidLSB = in.readLong();

    long tokens = in.readLong();

}


查看完整回答
反对 回复 2022-11-30
  • 1 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号