convert .zip file into NSData

て烟熏妆下的殇ゞ 提交于 2019-12-11 01:32:59

问题


Hey, Is it correct to initialize an NSData with a zip file? I want to convert a zip file into NSData and construct another file with the data (in simple language 'copy it'). I have the code as:

NSURL *theFileUrl = [NSURL URLWithString: @"file://localhost/Users/xxx/Desktop/testZippedFile.zip"];

NSData *data = [NSData dataWithContentsOfURL: theFileUrl];

When I, NSLog(@"Data: %@", data) , i do get some output but when I try to initialize an NSString with this data, it doesn't work:

 NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
`NSLog(@"String: %@", string)`

I get the log as: String: PK

Can anyone point out my mistakes please. Thanks in advance!


回答1:


Why do it that way? NSFileManager will do it for you :)

[[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:nil];

However, this only works for files that are local - if you want to copy a file from a server, you should have a look at NSURLConnection to load the data and then NSData's writeToFile:atomically: method to save the contents to the file system (found here.)




回答2:


PK is the output you should expect.
The first 2 Characters in every zip-file are PK. Then there are some unprintable chars and at some point after those there is a character with a value of 0
If you create an NSString out of NSData all values up to the first 0-value are taken into account.

NEVER convert binary data into NSString.



来源:https://stackoverflow.com/questions/3891149/convert-zip-file-into-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!