在java中实现fread(readInt)

问题描述

我正在尝试将读取 C++ 二进制文件的程序转换为 java。该文件采用小端格式。

fread(n,sizeof (unsigned),1,inputFile);

上面的 C++ 代码片段将 1 个整数读入整数变量 'n'。

我目前正在使用这种方法来完成同样的事情:

public static int readInt(RandomAccessFile inputStream) throws IOException {
    int retVal;
    byte[] buffer = new byte[4];
    inputStream.readFully(buffer);
    ByteBuffer wrapped = ByteBuffer.wrap(buffer);
    wrapped.order(ByteOrder.LITTLE_ENDIAN);
    retVal = wrapped.getInt();
    return retVal;
}

但此方法有时与 c++ 示例的结果不同。我无法确定文件的哪些部分导致此方法失败,但我知道确实如此。例如,当读取文件的一部分时,我的 readInt 方法返回 543974774,但 C++ 版本返回 1

有没有更好的方法来读取 Java 中的小端值?还是我的实现中有一些明显的缺陷?任何帮助了解我可能出错的地方,或者我如何才能以更有效的方式读取这些值,将不胜感激。

更新: 我使用 RandomAccessFile 是因为我经常需要 RandomAccessFile 在 java 中提供的 fseek 功能

解决方法

543974774 是十六进制的 206C6576。

行星上没有将 206C6576 变成“1”的字节序。因此,问题在于您没有阅读您认为正在阅读的内容:如果 C 代码正在读取 4 个字节(甚至是一个变量,未知字节数)并将其转换为“1”,那么您的 Java 代码是读取的字节不同 - 您的 C 代码和 java 代码不同步:例如,在某些时候,您的 C 代码读取了 2 个字节,而您的 java 代码读取了 4 个字节,反之亦然。

问题不在于您的 Sub GetOutlookData() Dim OutlookApp As Outlook.Application Dim OutlookNamespace As Namespace Dim Folder As MAPIFolder Dim OutlookMail As Variant Dim i As Integer Dim FolderItems As Items Set OutlookApp = New Outlook.Application Set OutlookNamespace = OutlookApp.GetNamespace("MAPI") Set Folder = OutlookNamespace.Folders("FOLLOWUPS") Set Folder = Folder.Folders("Inbox") i = 1 For Each OutlookMail In Folder.Items If OutlookMail.ReceivedTime >= Range("email_Receipt_Date") Then Range("email_Subject").Offset(i,0) = OutlookMail.Subject Range("email_Date").Offset(i,0) = OutlookMail.ReceivedTime Range("email_Sender").Offset(i,0) = OutlookMail.SenderName Range("email_Body").Offset(i,0) = OutlookMail.Body i = i + 1 End If Next OutlookMail Set Folder = Nothing Set OutlookNamespace = Nothing Set OutlookApp = Nothing End Sub 方法 - 每次都能正确完成工作。