如何确定文件是否为zip文件? [英] How can I determine if a file is a zip file?

查看:206
本文介绍了如何确定文件是否为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.

推荐答案

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

According to http://www.pkware.com/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文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆