开发者

Reading characters from a file written with .net

I'm trying to use java to read a string from a file that was written with a .net binaryWriter.

I think the problem is because the .net binary writer uses some 7 bit format for it's strings. By researching online, I came across this code that is supposed to function like the binary reader's readString() method. This is in my CSDataInputStream class that extends DataInputStream.

public String readStringCS()  throws IOException {
    int stringLength = 0;
    boolean stringLengthParsed = false;
    int step = 0;
    while(!stringLengthParsed) {
        byte part = readByte();
        stringLengthParsed = (((int)part >> 7) == 0);
        int partCutter = part & 127;
        part = (byte)partCutter;
        int toAdd = (int)part << (step*7);
        stringLength += toAdd;
        step++;
    }
    char[] chars = new char[stringLength];
    for(int i = 0; i < stringLength; i++) {
        c开发者_运维问答hars[i] = readChar();
    }
    return new String(chars);
}

The first part seems to be working as it is returning the correct amount of characters (7). But when it reads the characters they are all Chinese! I'm pretty sure the problem is with DataInputStream.readChar() but I have no idea why it isn't working... I have even tried using

Character.reverseBytes(readChar());

to read the char to see if that would work, but it would just return different Chinese characters.

Maybe I need to emulate .net's way of reading chars? How would I go about doing that?

Is there something else I'm missing?

Thanks.


Okay, so you've parsed the length correctly by the sounds of it - but you're then treating it as the length in characters. As far as I can tell from the documentation it's the length in bytes.

So you should read the data into a byte[] of the right length, and then use:

return new String(bytes, encoding);

where encoding is the appropriate coding based on whatever was written from .NET... it will default to UTF-8, but it can be specified as something else.

As an aside, I personally wouldn't extend DataInputStream - I would compose it instead, i.e. make your type or method take a DataInputStream (or perhaps just take InputStream and wrap that in a DataInputStream). In general, if you favour composition over inheritance it can make code clearer and easier to maintain, in my experience.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜