如何确定文件是否为zip文件?

编程入门 行业动态 更新时间:2024-10-21 05:43:36
本文介绍了如何确定文件是否为zip文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要确定我应用的文档目录中的文件是否是zip文件。文件名不能用于进行此确定。因此,我需要能够读取MIME类型或查找仅适用于拉链的其他属性。

I need to determine if a file in my app's documents directory is a zip file. The file name cannot be used in making this determination. So I will need to be able read the MIME type or find some other property that only applies to zips.

注意:需要将整个文件放入内存的解决方案是因文件可能非常大而不理想。

NOTE: A solution that requires putting the entire file into memory is not ideal as files could potentially be pretty large.

推荐答案

根据 www.pkware/documents/casestudies/APPNOTE.TXT ,a ZIP文件以本地文件开头标题签名

According to www.pkware/documents/casestudies/APPNOTE.TXT, a ZIP file starts with the "local file header signature"

0x50, 0x4b, 0x03, 0x04

所以读取前4个字节就足以检查文件是否可能是ZIP文件。 只有在您真正尝试提取文件时才能做出明确的决定。

so it is sufficient to read the first 4 bytes to check if the file is possibly a ZIP file. A definite decision can only be made if you actually try to extract the file.

有许多方法可以读取第一个4个字节的文件。您可以使用NSFileHandle, NSInputStream,打开/读取/关闭,....所以这只应作为一个可能的例子:

There are many methods to read the first 4 bytes of a file. You can use NSFileHandle, NSInputStream, open/read/close, ... . So this should only be taken as one possible example:

NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/path/to/file"]; NSData *data = [fh readDataOfLength:4]; if ([data length] == 4) { const char *bytes = [data bytes]; if (bytes[0] == 'P' && bytes[1] == 'K' && bytes[2] == 3 && bytes[3] == 4) { // File starts with ZIP magic ... } }

更多推荐

如何确定文件是否为zip文件?

本文发布于:2023-11-29 17:16:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647064.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   zip

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!