简体   繁体   English

Java到Objective-C-等同于readUTF()的方法?

[英]Java to Objective-C - Equivalent method to readUTF()?

Is there any equivalent method for readUTF() from java in objective C? 是否有任何等效的方法可以从目标C中的Java中读取readUTF()?

Here's a snippet that I need to convert to objective C: 这是我需要转换为目标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. 一种方法是将整个文件读入字节数组(或NSData实例),然后遍历数据。 When you have to read a string, you call stringWithUTF8String: of NSString and then skip the correct number of bytes. 当必须读取字符串时,可以调用NSString stringWithUTF8String: ,然后跳过正确的字节数。 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. 我使用strlen是因为它不了解Unicode并只计算字节而不是字符。

This should work if you don't have any code points above 00FFFF. 如果您没有00FFFF以上的任何代码点,则此方法应该起作用。 If you have, I'll need to dig deeper into the modified UTF-8 format used by Java's binary data streams. 如果有的话,我将需要更深入地研究Java二进制数据流使用的经过修改的UTF-8格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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