如何保存文件的文件夹?(How to save file in the documents fold

2019-06-25 12:32发布

我试图将数据保存在iPhone 5.1模拟器的文件夹。

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myData.json"];

if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath]) {
    NSLog(@"Writable");
}else {
    NSLog(@"Not Writable");
}

我有一直“不可写”。 任何的想法? 请帮我。

Answer 1:

也许是因为你还没有创建的文件,你测试的文件不存在。 :)

你可以这样做是为了发现问题,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myData.json"];
NSLog(@"filePath %@", filePath);

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // if file is not exist, create it.
    NSString *helloStr = @"hello world";
    NSError *error;
    [helloStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}

if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath]) {
    NSLog(@"Writable");
}else {
    NSLog(@"Not Writable");
}


Answer 2:

试试这个:

NSString *data = .... // your json representation
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myData.json"];
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];


Answer 3:

换出你的[NSString stringWithFormat:][NSString stringByAppendingPathComponent:] 。 这将决定你建立一个可行路径的能力,或者说我的经验告诉我。

此外,这样的事情在模拟器VS真实设备写入时出现。 模拟器是一个很大的宽容,当你保存的东西在错误的路径不是设备会,而且经常你会得到的I / O做工精细只碰到臭名昭著的“它的工作原理在模拟器! 坑。 stringWithFormat:只有一个办法往里钻



Answer 4:

获得文件目录路径

+(NSURL *)getDocumentsDirectoryPath
{
    return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}

将数据写入到文件结尾

+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];

    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    if(fileHandler == nil) {
        [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
        fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    } else {
        textTobeSaved = [NSString stringWithFormat:@"\n-----------------------\n %@",textTobeSaved];
        [fileHandler seekToEndOfFile];
    }

    [fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandler closeFile];
}


文章来源: How to save file in the documents folder?