亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字節從文件中讀取錯誤?

字節從文件中讀取錯誤?

泛舟湖上清波郎朗 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)?tm(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 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號