c# - 如何将数字写入文件并使其在 Java 和 C# 之间可读

标签 c# java interop inputstream outputstream

我遇到了同一程序的两个版本之间的“兼容性”问题,第一个版本是用 Java 编写的,第二个版本是用 C# 编写的。

我的目标是将一些数据写入文件(例如,在 Java 中),例如数字序列,然后能够在 C# 中读取它。显然,该操作应该以相反的顺序进行。

例如,我想按顺序写入 3 个数字,用以下模式表示:

  • 第一个数字为一个“字节”(4 位)
  • 第二个数字为一个“整数”(32 位)
  • 第三个数字为一个“整数”(32 位)

因此,我可以按以下顺序放入一个新文件:2(作为字节)、120(作为 int32)、180(作为 int32)

在Java中,编写过程大致是这样的:

FileOutputStream outputStream;
byte[] byteToWrite;
// ... initialization....

// first byte
outputStream.write(first_byte);

// integers
byteToWrite = ByteBuffer.allocate(4).putInt(first_integer).array();
outputStream.write(byteToWrite);
byteToWrite = ByteBuffer.allocate(4).putInt(second_integer).array();
outputStream.write(byteToWrite);

outputStream.close();

阅读部分如下:

FileInputStream inputStream;
ByteBuffer byteToRead;
// ... initialization....

// first byte
first_byte = inputStream.read();

// integers
byteToRead = ByteBuffer.allocate(4);
inputStream.read(byteToRead.array());
first_integer = byteToRead.getInt();

byteToRead = ByteBuffer.allocate(4);
inputStream.read(byteToRead.array());
second_integer = byteToRead.getInt();

inputStream.close();

C# 代码如下。写作:

FileStream fs;
byte[] byteToWrite;
// ... initialization....

// first byte
byteToWrite = new byte[1];
byteToWrite[0] = first_byte;
fs.Write(byteToWrite, 0, byteToWrite.Length);

// integers
byteToWrite = BitConverter.GetBytes(first_integer);
fs.Write(byteToWrite, 0, byteToWrite.Length);
byteToWrite = BitConverter.GetBytes(second_integer);
fs.Write(byteToWrite, 0, byteToWrite.Length);

阅读:

FileStream fs;
byte[] byteToWrite;
// ... initialization....

// first byte
byte[] firstByteBuff = new byte[1];
fs.Read(firstByteBuff, 0, firstByteBuff.Length);
first_byte = firstByteBuff[0];

// integers
byteToRead = new byte[4 * 2];
fs.Read(byteToRead, 0, byteToRead.Length);
first_integer = BitConverter.ToInt32(byteToRead, 0);
second_integer = BitConverter.ToInt32(byteToRead, 4);

请注意,当同一 Java/C# 版本的程序写入和读取文件时,这两个过程都有效。问题是当我尝试从 C# 版本读取 Java 程序编写的文件时,反之亦然。读取的整数始终是“奇怪”的数字(例如 -1451020...)。

与 C# 相比,Java 存储和读取 32 位整数值(总是有符号,对吧?)的方式肯定存在兼容性问题。如何处理这个问题?

最佳答案

这只是一个字节顺序问题。你可以用我的MiscUtil library从 .NET 读取大端数据。

但是,我强烈建议您对 Java 和 .NET 采用更简单的方法:

或者,考虑仅使用文本。

关于c# - 如何将数字写入文件并使其在 Java 和 C# 之间可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22560406/

相关文章:

c# - 在不打开 Word 的情况下使用 Interop DLL 打开 Word 文档?

c# - 我可以在 XAML 中处理抛出的异常吗?

c# - 错误 "Class does not contain a definition for method"但方法存在

java - Waffle Kerberos SSO - 模拟更改 tomcat 用户

c# - 当从 C# 调用/编码(marshal)此结构到 C-DLL 时,为什么此字符串为空?

c# - 如何使用互操作将新的 session 请求添加到 Outlook 日历?

c# - 绑定(bind) DataGridView 中的组合框

c# - 通用内置 EventArgs 只包含一个属性?

Java:JButton 打开另一个我可以输入的 JFrame

java - NIO GZIP 压缩和文件复制