reading c# binary files in java

后端 未结 3 1851
无人共我
无人共我 2021-01-07 03:05

I have a program in C# .net which writes 1 integer and 3 strings to a file, using BinaryWriter.Write().

Now I am programming in Java (for Android, and

相关标签:
3条回答
  • 2021-01-07 03:31

    There is a very good explanation of the format used by BinaryWriter in this question Right Here it should be possible to read the data with a ByteArrayInputStream and write a simple translator.

    0 讨论(0)
  • 2021-01-07 03:32

    I wrote a quick example on how to read .net's binaryWriter format in java here

    excerpt from link:

       /**
     * 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;
    }
    
    0 讨论(0)
  • 2021-01-07 03:48

    As its name implies, BinaryWriter writes in binary format. .Net binary format to be precise, and as java is not a .Net language, it has no way of reading it. You have to use an interoperable format.

    You can choose an existing format, like xml or json or any other interop format.

    Or you can create your own, providing your data is simple enough to make it this way (it seems to be the case here). Just write a string to your file (using a StreamWriter for instance), provided you know your string's format. Then read your file from java as a string and parse it.

    0 讨论(0)
提交回复
热议问题