将 .zip 文件转换为 NSData

发布于 2024-09-26 20:06:18 字数 580 浏览 2 评论 0原文

嘿,用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的背包 2024-10-03 20:06:18

为什么要这样做? NSFileManager 将为您执行此操作:)

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

但是,这仅适用于本地文件 - 如果您想从服务器复制文件,您应该查看 NSURLConnection 加载数据,然后使用 NSData 的 writeToFile:atomically: 方法将内容保存到文件系统(在这里找到。)

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.)

忘年祭陌 2024-10-03 20:06:18

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文