字节从文件中读取错误?

所以,我试图将 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。


我用“”连接字节以顺便打印它。


泛舟湖上清波郎朗
浏览 161回答 1
1回答

墨色风雨

不要用于FileReader从文件中读取原始字节。改用FileInputStream。的问题FileReader是它通过尝试使用某种字符编码(如果没有给出则使用默认编码)来解码字节,从而从文件中读取chars,而不是。bytesbytes = 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();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java