【问题标题】:reading c# binary files in java在java中读取c#二进制文件
【发布时间】:2012-07-08 02:58:41
【问题描述】:

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

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

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

java.io.UTFDataFormatException:字节 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();

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

【问题讨论】:

  • 你用什么编码写的文件?您必须使用 same 编码来读取它们。
  • 如果您打算跨平台读取数据,则应使用可互操作的格式。

标签: c# java binary


【解决方案1】:

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

摘自链接:

   /**
 * 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;
}

【讨论】:

  • 您想在您的答案中添加一个摘录,这样如果链接失效,您在此处的答案仍然有用吗?
  • 好主意,我已将其添加到我的原始帖子中。
【解决方案2】:

顾名思义,BinaryWriter 以二进制格式写入。准确地说是.Net 二进制格式,并且由于java 不是.Net 语言,它无法读取它。您必须使用可互操作的格式。

您可以选择现有格式,如 xml 或 json 或任何其他互操作格式。

或者您可以创建自己的数据,前提是您的数据足够简单,可以采用这种方式(这里似乎就是这种情况)。只要您知道字符串的格式,只需将字符串写入文件(例如使用 StreamWriter)。然后从java中读取你的文件作为一个字符串并解析它。

【讨论】:

    【解决方案3】:

    在这个问题Right Here中对BinaryWriter使用的格式有很好的解释,应该可以用ByteArrayInputStream读取数据并编写一个简单的翻译器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2011-09-03
      • 2016-01-15
      • 1970-01-01
      • 2015-07-27
      相关资源
      最近更新 更多