简体   繁体   中英

Java to Objective-C - Equivalent method to readUTF()?

Is there any equivalent method for readUTF() from java in objective C?

Here's a snippet that I need to convert to objective C:

FileInputStream in = new FileInputStream(mapfile.dat);
ObjectInputStream si = new ObjectInputStream(in);
si.readUTF();

boolean create = si.readBoolean();
si.readBoolean();
if (create) {

    si.readInt();
    si.readInt();
    si.readInt();
    si.readInt();
    int num=si.readInt();
    if (num>0) {
            for (int i=0;i<num;i++) {
                    si.readObject();
            }
            si.readInt();
    }
    num=si.readInt();
}

//.............

How big is the file you're reading from? If it's modestly sized, you can use this:

NSString * string = [ NSString stringWithContentsOfFile:pathToFile 
                                               encoding:NSUTF8StringEncoding error:NULL ] ;

An approach could be to read the whole file into a byte array (or NSData instance) and then to iterate through the data. When you have to read a string, you call stringWithUTF8String: of NSString and then skip the correct number of bytes. The encoded string has two null bytes at the end.

So reading the string could look like this:

 NSData* data = ...;
 const char* dataPtr = [data bytes];

 // read data and move dataPtr

 // read string
 NSString str = [NSString stringWithUTF8String: dataPtr];
 dataPtr += strlen(dataPtr) + 2;

I'm using strlen because it doesn't know about Unicode and counts the bytes and not the characters.

This should work if you don't have any code points above 00FFFF. If you have, I'll need to dig deeper into the modified UTF-8 format used by Java's binary data streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM