gpt4 book ai didi

c# - 在java中读取c#二进制文件

转载 作者:行者123 更新时间:2023-11-30 07:24:38 24 4
gpt4 key购买 nike

我有一个 C# .net 程序,它使用 BinaryWriter.Write() 将 1 个整数和 3 个字符串写入文件。

现在我正在用 Java 编程(适用于 Android,我是 Java 的新手),我必须访问以前使用 C# 写入文件的数据。

我尝试使用 DataInputStream.readInt()DataInputStream.readUTF(),但无法获得正确的结果。我通常会得到一个 UTFDataFormatException:

java.io.UTFDataFormatException: malformed input around byte 21

或者我得到的 Stringint 是错误的...

FileInputStream fs = new FileInputStream(strFilePath);
DataInputStream ds = new DataInputStream(fs);
int i;
String str1,str2,str3;
i=ds.readInt();
str1=ds.readUTF();
str2=ds.readUTF();
str3=ds.readUTF();
ds.close();

这样做的正确方法是什么?

最佳答案

我写了一个关于如何在 java 中读取 .net 的 binaryWriter 格式的快速示例 here

摘自链接:

   /**
* Get string from binary stream. >So, if len < 0x7F, it is encoded on one
* byte as b0 = len >if len < 0x3FFF, is is encoded on 2 bytes as b0 = (len
* & 0x7F) | 0x80, b1 = len >> 7 >if len < 0x 1FFFFF, it is encoded on 3
* bytes as b0 = (len & 0x7F) | 0x80, b1 = ((len >> 7) & 0x7F) | 0x80, b2 =
* len >> 14 etc.
*
* @param is
* @return
* @throws IOException
*/
public static String getString(final InputStream is) throws IOException {
int val = getStringLength(is);

byte[] buffer = new byte[val];
if (is.read(buffer) < 0) {
throw new IOException("EOF");
}
return new String(buffer);
}

/**
* Binary files are encoded with a variable length prefix that tells you
* the size of the string. The prefix is encoded in a 7bit format where the
* 8th bit tells you if you should continue. If the 8th bit is set it means
* you need to read the next byte.
* @param bytes
* @return
*/
public static int getStringLength(final InputStream is) throws IOException {
int count = 0;
int shift = 0;
boolean more = true;
while (more) {
byte b = (byte) is.read();
count |= (b & 0x7F) << shift;
shift += 7;
if((b & 0x80) == 0) {
more = false;
}
}
return count;
}

关于c# - 在java中读取c#二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11382728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com