简体   繁体   English

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

[英]How can I determine if a file is a zip file?

I need to determine if a file in my app's documents directory is a zip file. 我需要确定我的应用程序文档目录中的文件是否是zip文件。 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. 所以我需要能够读取MIME类型或找到一些仅适用于拉链的其他属性。

NOTE: A solution that requires putting the entire file into memory is not ideal as files could potentially be pretty large. 注意:需要将整个文件放入内存的解决方案并不理想,因为文件可能非常大。

According to http://www.pkware.com/documents/casestudies/APPNOTE.TXT , a ZIP file starts with the "local file header signature" 根据http://www.pkware.com/documents/casestudies/APPNOTE.TXT,ZIP文件以“本地文件头签名”开头

0x50, 0x4b, 0x03, 0x04

so it is sufficient to read the first 4 bytes to check if the file is possibly a ZIP file. 所以读取前4个字节就足以检查文件是否可能是ZIP文件。 A definite decision can only be made if you actually try to extract the file. 只有在您真正尝试提取文件时才能做出明确的决定。

There are many methods to read the first 4 bytes of a file. 许多方法可以读取文件的前4个字节。 You can use NSFileHandle, NSInputStream, open/read/close, ... . 您可以使用NSFileHandle,NSInputStream,打开/读取/关闭,.... 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 ...
    }
}

Swift 4 version: Swift 4版本:

if let fh = FileHandle(forReadingAtPath: "/path/to/file") {
    let data = fh.readData(ofLength: 4)
    if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
        // File starts with ZIP magic ...
    }
    fh.closeFile()
}

Try this 试试这个

NSWorkspace *ws = [NSWorkspace sharedWorkspace];
NSString *description = [ws localizedDescriptionForType:[ws typeOfFile:@"/full/path/to/file" error:nil]];

Or for mime this 或者对于哑剧而言

+ (NSString*) mimeTypeForFileAtPath: (NSString *) path {
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return nil;
    }
    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[path pathExtension], NULL);
    CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
    CFRelease(UTI);
    if (!mimeType) {
        return @"application/octet-stream";
    }
    return [NSMakeCollectable((NSString *)mimeType) autorelease];
}

I'd just use file , then grep if it has the text "zip" or "Zip Archive" to be safe. 我只是使用文件 ,然后grep如果它有文本“zip”或“Zip存档”是安全的。

if file -q $FILENAME | grep "Zip archive"; then
  echo "zip";
else
  echo "not zip";
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM