如何在c#中读取使用Java程序编写的二进制文件,反之亦然
本文关键字:程序 二进制文件 反之亦然 Java 读取 | 更新日期: 2023-09-27 18:13:35
下面是Java程序。写和读操作显示我正确的值。但是当我在c#中阅读相同的二进制文件时。我得到了不正确的值。
JAVA程序
///////////////////////////////////////////////////////////////////////////
public class Main {
public static void main(String[] args) {
// ReadFile o = new ReadFile();
// o.Read("csharp123.dat");
WriteFile w = new WriteFile();
w.Write("java123.dat");
w = null;
ReadFile r = new ReadFile();
r.Read("java123.dat");
r = null;
}
}
/////////////////////////////////////////////////////////////////////
class WriteFile {
Random m_oRN = new Random();
private int getRandom()
{
return m_oRN.nextInt(100);
}
public void Write(String strFileName) {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(strFileName));
dos.writeInt(123);
dos.writeInt(234);
dos.writeInt(345);
dos.flush();
dos.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
///////////////////////////////////////////////////////////////////////////
//
class ReadFile {
public void Read(String strFileName) {
try {
File fp = new File(strFileName);
FileInputStream fis = new FileInputStream(fp);
DataInputStream din = new DataInputStream(fis);
int count = (int) (fp.length() / 4);
for (int i = 0; i < count; i++) {
System.out.println(din.readInt());
}
din.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//---------------------------------------------------c#项目
private void msViewRead_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
string strLastPath = RegistryAccess.ReadRegistryString("LastSavedPath");
dlg.InitialDirectory = strLastPath.Length == 0 ? Application.StartupPath : strLastPath;
dlg.Filter = "Data file (*.dat)|*.dat|All file (*.*)|*.*||";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() != DialogResult.OK)
return;
this.Cursor = Cursors.WaitCursor;
string strValue = String.Empty;
using (var fs = File.Open(dlg.FileName, FileMode.Open))
using (var br = new BinaryReader(fs))
{
var vPos = 0;
var vLen = (int)br.BaseStream.Length;
while (vPos < vLen)
{
strValue += br.ReadInt32();
strValue += ''n';
vPos += sizeof(int);
}
}
this.Cursor = Cursors.Default;
MessageBox.Show(strValue, "Read Binary File");
}
这里是垃圾数据
很可能您的问题是端序。DataOutputStream
首先写入高字节(大端序),. net的BinaryReader
最后写入高字节(小端序)。你需要一种方法来反转字节顺序。