如何在Objective c中获取目录中文件的创建日期

Posted

技术标签:

【中文标题】如何在Objective c中获取目录中文件的创建日期【英文标题】:How do you get the creation date of files in a directory in Objective c 【发布时间】:2014-01-06 20:42:56 【问题描述】:

我正在学习 Objective-C,我正在将 Applescript 实用程序转换为 Objective-C

我需要了解如何获取目录中所有文件的NSFileCreationDate,以便将最新文件复制到另一个位置。我不知道如何获取目录中每个文件的NSFileCreationDate

此代码获取目录列表,但每次我尝试获取 NSFileCreationDate 时,它都会给我封闭文件夹的 NSFileCreationDate

我必须读取一个 plist 文件才能获得备份位置的路径。

    为备份位置读取 plist 文件 获取文件的创建日期

    将最新的文件复制到 * wholepath , 桌面上的文件

    NSString filePath = [@"~/Library/Preferences/com.viive.Viive.plist" stringByExpandingTildeInPath]; NSMutableDictionary plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

    NSString *value;
    value = [plistDict objectForKey:@"backupPath"];
    
    
    NSFileManager *filemgr;
    NSArray *filelist;
    filemgr = [NSFileManager defaultManager];
    filelist = [filemgr contentsOfDirectoryAtPath:value error: nil];
    NSArray *array = filelist;
    NSUInteger index = 0;
    for (id element in array) 
    NSLog(@"Element at index %lu is: %@", (unsigned long)index, element);
    index++;
    
    NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:////     error:nil];
    NSDate *result = [fileAttribs fileCreationDate]; //or fileModificationDate
    NSLog(@"%@",result);
    
    //////
    
     NSString* desktop = [@"~/Desktop/LOGS-I-NEED-" stringByExpandingTildeInPath];
        NSString* computername = [[NSHost currentHost] localizedName];
        NSString* wholepath = [desktop stringByAppendingString:computername];
    

我已经用谷歌搜索了这个信息,因为我是新手,所以我找到的答案对我来说没有多大意义。如果有人知道更好的方法,我会全力以赴。

谢谢大家!!

【问题讨论】:

【参考方案1】:

这应该会有所帮助:

for (NSString file in array) 
    NSLog (@"%@", file);
    NSString *path = [filePath stringByAppendingPathComponent: file];
    NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    NSDate *result = [fileAttribs fileCreationDate]; //or fileModificationDate
    NSLog(@"%@",result);
 

【讨论】:

这段代码给了我 -[__NSCFString path]: unrecognized selector sent to instance 0x106107c30 我得到 (null) 然后如果我再试一次,我会得到一个文件内容列表,但后来我得到这个 *** -[__NSArrayM objectAtIndex:]: index 34 beyond bounds [0 .. 33 ] 这可以改进一点。首先,使用快速枚举而不是索引数组。其次,使用stringByAppendingPathComponent: 而不是stringWithFormat: 更新了枚举,但仍然得到 - 不兼容的指针类型将 NSArray* 发送到 NSString* 类型的参数 @Breathable:感谢您的建议。我已经更新了示例。【参考方案2】:

以下可能会有所帮助

// This is the main routine to read the contents of a directory (into array of URL)
- (NSArray *)readDirectory:(NSString *)path error:(NSError **)error 
    NSURL *url = [NSURL fileURLWithPath:path isDirectory:YES];
    NSArray *array = [[NSFileManager new]
                      contentsOfDirectoryAtURL:url
                      includingPropertiesForKeys:properties
                      options:(NSDirectoryEnumerationSkipsPackageDescendants |
                               ((showHiddenFiles | unHideDir| unHideAllDir) ? 0 : NSDirectoryEnumerationSkipsHiddenFiles))
                      error:error];
    if (unHideDir) 
        NSIndexSet *unDotted = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger index, BOOL *stop) 
            NSString *name;
            [obj getResourceValue:&name forKey:NSURLNameKey error:nil];
            if ([name characterAtIndex:0] == '.')   return NO;  // exclude .files
            return YES;
        ];
        return [array objectsAtIndexes:unDotted];
    
    return array;

您可以省略unHideDir((showHiddenFiles | unHideDir| unHideAllDir)

这依赖于properties 的数组。我在initialize中设置了这个

+ (void)initialize 
    if (self == [DirectoryItem class]) 
        leafNode = [[NSMutableArray alloc] init];
        [self loadPreferences];
        properties = [NSArray arrayWithObjects:
                      NSURLNameKey,
                      NSURLFileSizeKey, NSURLIsAliasFileKey, NSURLIsPackageKey,
                      NSURLIsDirectoryKey, NSURLIsSymbolicLinkKey, NSURLIsRegularFileKey,
                      NSURLCreationDateKey, NSURLContentModificationDateKey,
                      NSURLLocalizedTypeDescriptionKey, nil];
        dirSortDescriptor = [NSArray arrayWithObject:
                             [[NSSortDescriptor alloc] initWithKey:COLUMNID_NAME
                                                         ascending:YES
                                                          selector:@selector(localizedStandardCompare:)]];
    

你可以用类似的东西解压日期

NSDate *tempDate;
[path getResourceValue:&tempDate forKey:NSURLCreationDateKey error:nil];
if ([tempDate timeIntervalSince1970] < 24*3600) tempDate = nil;
cDate = [tempDate copy];
[path getResourceValue:&tempDate forKey:NSURLContentModificationDateKey error:nil];
wDate = [tempDate copy];

【讨论】:

【参考方案3】:

在你们的帮助下,我找到了正确的方向。 感谢所有评论的人!

这是我的最终代码,可以帮助遇到类似问题的其他人。

NSString *s = [NSString stringWithFormat:@"tell application \"12345\" to backup"];
NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s];
[as executeAndReturnError:nil];

///////

NSString *filePath = [@"~/Library/Preferences/com.12345.12345.plist" stringByExpandingTildeInPath];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

NSString *value;
value = [plistDict objectForKey:@"backupPath"];

/////

NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:@"YYY-MM-dd'T'HH:MM:ss'"];
NSDate *maxdate = [NSString stringWithFormat:@"1900-01-01 00:00:00 +0000"];

NSFileManager *filemgr;
NSArray *filelist;

filemgr = [NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:value error: nil];
NSArray *array = filelist;
NSUInteger index = 0;
NSString *currentdb;
for (id element in array) 
    NSLog(@"Element at index %lu is: %@", (unsigned long)index, element);

    NSString* slash = @"/";
    NSString* elementwithpath = value;
    NSString* wholepathh = [elementwithpath stringByAppendingString:slash];
    wholepathh = [wholepathh stringByAppendingString:element];


    NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:wholepathh error:nil];
    NSDate *result = [fileAttribs fileCreationDate]; //or fileModificationDate
    NSLog(@"%@",result);
    index++;

    if (result > maxdate)
    
        maxdate = result;
        currentdb = wholepathh;
    
    NSLog(wholepathh);

NSLog(currentdb);

/////

NSString* desktop = [@"~/Desktop/LOGS-I-NEED-" stringByExpandingTildeInPath];
NSString* computername = [[NSHost currentHost] localizedName];
NSString* wholepath = [desktop stringByAppendingString:computername];
NSString* slash = @"/";

NSString* filename = [[currentdb lastPathComponent] stringByDeletingPathExtension];


NSString* totalpath =[ wholepath stringByAppendingString:slash];
NSString* finalpath =[ totalpath stringByAppendingString:filename];

NSError * error = nil;
filemgr = [NSFileManager defaultManager];


([filemgr copyItemAtPath:currentdb toPath:finalpath error:&error]);

if (error != nil)

    NSLog(@"error creating directory: %@", error);
    //..

else

    NSLog(@"Copying the 12345 Backup worked!");

【讨论】:

以上是关于如何在Objective c中获取目录中文件的创建日期的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Objective-C 的 NSDocument 目录中保存和获取多个 pdf 文件?

如何在Objective c中获取音频文件的某些部分

从文档目录中的文件夹创建 ZIP 文件 - Objective C (ARC)

Objective C 中的目录大小

如何在Objective C代码中查找目录修改日期的所有内容

在 Objective C 中获取文件的内容类型