在java中读取c#二进制文件
我在C#.net中有一个程序,它使用BinaryWriter.Write()
将1个整数和3个字符串写入文件。
现在我用Java编程(对于Android,我是Java的新手),我必须访问以前使用C#写入文件的数据。
我尝试使用DataInputStream.readInt()
和DataInputStream.readUTF()
,但我无法获得正确的结果。 我经常得到一个UTFDataFormatException
:
java.io.UTFDataFormatException:字节21周围的格式错误的输入
或者我得到的String
和int
是错的……
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();
这样做的正确方法是什么?
顾名思义,BinaryWriter以二进制格式编写。 .Net二进制格式要准确,而且java不是.Net语言,它无法读取它。 您必须使用可互操作的格式。
您可以选择现有格式,如xml或json或任何其他互操作格式。
或者您可以创建自己的数据,只要您的数据足够简单(这似乎就是这种情况)。 只需要知道字符串的格式,只需在文件中写一个字符串(例如使用StreamWriter)。 然后从java中读取您的文件作为字符串并解析它。
我写了一个关于如何在java中读取.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; }
BinaryWriter在这个问题中使用的格式有一个很好的解释。在这里 ,应该可以用ByteArrayInputStream读取数据并编写一个简单的翻译器。