我需要确定我应用的文档目录中的文件是否是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文件?
发布评论