C# 如何将数字写入文件并使其在Java和C之间可读#
我正在研究同一程序的两个版本之间的“兼容性”问题,第一个是用Java编写的,第二个是用C#编写的端口 我的目标是将一些数据写入一个文件(例如,在Java中),比如一个数字序列,然后能够用C#读取它。显然,操作应该以相反的顺序进行 例如,我想按顺序写3个数字,用以下模式表示:C# 如何将数字写入文件并使其在Java和C之间可读#,c#,java,interop,inputstream,outputstream,C#,Java,Interop,Inputstream,Outputstream,我正在研究同一程序的两个版本之间的“兼容性”问题,第一个是用Java编写的,第二个是用C#编写的端口 我的目标是将一些数据写入一个文件(例如,在Java中),比如一个数字序列,然后能够用C#读取它。显然,操作应该以相反的顺序进行 例如,我想按顺序写3个数字,用以下模式表示: 第一个数字为一个“字节”(4位) 第二个数字作为一个“整数”(32位) 第三个数字作为一个“整数”(32位) 因此,我可以按以下顺序放入一个新文件:2(作为字节)、120(作为int32)、180(作为int32) 在J
- 第一个数字为一个“字节”(4位)
- 第二个数字作为一个“整数”(32位)
- 第三个数字作为一个“整数”(32位)
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();
代码如下。写作:
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#version和viceversa中读取Java程序编写的文件时。读取的整数总是“奇怪”的数字(如-1451020…)
与C#相反,Java存储和读取32位整数值的方式(总是
有符号的,对吗?)肯定存在兼容性问题。如何处理这个问题?这只是一个永恒的问题。您可以使用my从.NET读取大端数据
但是,我强烈建议对Java和.NET使用一种更简单的方法:
- 在Java中,使用和。没有必要把
ByteBuffer
等复杂化
- 在.NET中,使用MiscUtil中的
EndianBinaryReader
,它扩展了(同样地,EndianBinaryWriter
for)
替换地,只考虑使用文本。
我会考虑使用像XML或JSON这样的标准格式来存储数据。然后,您可以使用Java和C#中的标准序列化程序来读/写文件。这种方法可以让您轻松地命名数据字段,从多种语言读取数据,如果有人在文本编辑器中打开文件,则很容易理解,并且更容易添加要序列化的数据
例如,您可以使用和读/写JSON。在C#中,该类可能如下所示:
它将序列化为
{"FirstValue":2,"SecondValue":5,"ThirdValue":-1}
同样,Java也会非常简单。您可以在每个库中找到如何读取/写入文件的示例
或者,如果阵列是数据的更好模型:
string serialized = JsonConvert.SerializeObject(new[] { 2, 5, -1 }); // [2,5,-1]
好的,谢谢,我会尽力的,但是我不能使用你的个人图书馆。有“标准”的东西吗?
string serialized = JsonConvert.SerializeObject(new[] { 2, 5, -1 }); // [2,5,-1]