11

我正在使用以下代码行将我的 yoyo.txt 文件保存在 Documents 文件夹中::

NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSLog(@"docDir is yoyo :: %@", docDir);
NSString *FilePath = [docDir stringByAppendingPathComponent:@"yoyo.txt"];

但是,我希望将我的文件保存在 yoyo 的文件夹中,即 Documents 文件夹中,即我想创建另一个名为“yoyo”的文件夹,然后将我的 yoyo.txt 文件保存到其中。我怎样才能做到这一点 ??谢谢。

4

3 回答 3

16

这是一个示例代码(假设manager[NSFileManager defaultManager]):

BOOL isDirectory;
NSString *yoyoDir = [docDir stringByAppendingPathComponent:@"yoyo"];
if (![manager fileExistsAtPath:yoyoDir isDirectory:&isDirectory] || !isDirectory) {
        NSError *error = nil;
        NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
                                                         forKey:NSFileProtectionKey];
        [manager createDirectoryAtPath:yoyoDir
           withIntermediateDirectories:YES
                            attributes:attr
                                 error:&error];
        if (error)
            NSLog(@"Error creating directory path: %@", [error localizedDescription]);
    }
于 2012-06-25T10:41:53.730 回答
11
+(void)createDirForImage :(NSString *)dirName
{
    NSString *path;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    path = [[paths objectAtIndex:0] stringByAppendingPathComponent:dirName];
    NSError *error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:path])    //Does directory already exist?
    {
        if (![[NSFileManager defaultManager] createDirectoryAtPath:path
                                       withIntermediateDirectories:NO
                                                        attributes:nil
                                                             error:&error])
        {
            NSLog(@"Create directory error: %@", error);
        }
    }

}
于 2012-06-25T10:45:18.127 回答
2

这里 dataPath 将是保存文件的最终路径

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/yoyo"];

        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
    }
    dataPath = [dataPath stringByAppendingPathComponent:@"/yoyo.txt"];
于 2013-10-09T05:35:21.787 回答