将 .zip 文件转换为 NSData
嘿,用 zip 文件初始化 NSData 是否正确?我想将 zip 文件转换为 NSData 并用数据构造另一个文件(用简单的语言“复制它”)。我的代码如下:
NSURL *theFileUrl = [NSURL URLWithString: @"file://localhost/Users/xxx/Desktop/testZippedFile.zip"];
NSData *data = [NSData dataWithContentsOfURL: theFileUrl];
当我 NSLog(@"Data: %@", data)
时,我确实得到了一些输出,但是当我尝试使用此数据初始化 NSString 时,它没有工作:
NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
`NSLog(@"String: %@", string)`
我得到的日志为:String:PK
任何人都可以指出我的错误吗? 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要这样做? NSFileManager 将为您执行此操作:)
但是,这仅适用于本地文件 - 如果您想从服务器复制文件,您应该查看 NSURLConnection 加载数据,然后使用 NSData 的 writeToFile:atomically: 方法将内容保存到文件系统(在这里找到。)
Why do it that way? NSFileManager will do it for you :)
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.)
PK 是您应该期望的输出。
每个 zip 文件中的前 2 个字符都是 PK。然后有一些不可打印的字符,在这些字符之后的某个时刻有一个值为 0 的字符
如果您从 NSData 创建 NSString,则将考虑第一个 0 值之前的所有值。
永远不要将二进制数据转换为 NSString。
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.