2

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();
}

//.............
Monolo
  • 18,205
  • 17
  • 69
  • 103
random
  • 10,238
  • 8
  • 57
  • 101

2 Answers2

0

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 ] ;
nielsbot
  • 15,922
  • 4
  • 48
  • 73
  • also, this will read a UTF-8 encoded file, whereas readUTF() reads a special variant of UTF-8... sounds like you probably don't have to worry about it? – nielsbot Feb 28 '12 at 06:36
  • I have a .dat file and the size is 600 KB. – random Feb 28 '12 at 06:48
  • oh. 600 KB. maybe on the large side? we need to know your intended use for the string in the file. Is it a single string? – nielsbot Feb 28 '12 at 06:54
  • 2
    omg sorry i didn't see you are decoding embeded objects... then this answer is not sufficient – nielsbot Feb 28 '12 at 06:55
0

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.

Codo
  • 75,595
  • 17
  • 168
  • 206
  • It returns a null value. 2012-02-28 16:19:28.624 ABC[2747:207] str (null) – random Feb 28 '12 at 10:45
  • My answer more or less answers the question "equivalent to readUTF8()". But could it be that you haven't even successfully read the header of the file? You do understand the file format at hand is complex: it has a header, it's divided into blocks, it can refer to objects earlier in the stream the reconstruct networks of objects including cycles? Have you read the [file format specification](http://docs.oracle.com/javase/6/docs/platform/serialization/spec/protocol.html)? – Codo Feb 28 '12 at 11:28