我在 C# .net 中有一个程序,它使用 .net 将 1 个整数和 3 个字符串写入文件BinaryWriter.Write()。
现在我正在用 Java 编程(对于 Android,我是 Java 新手),我必须访问以前使用 C# 写入文件的数据。
我尝试使用DataInputStream.readInt()and 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();
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
我在这里写了一个关于如何在 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2484 次 |
| 最近记录: |