10

我似乎无法让 nsdata 写入文件。任何想法我可能做错了什么。提前致谢。

NSString* filename = @"myfile.txt";

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:filename];    

if ([fileManager fileExistsAtPath:applicationDocumentsDir])
    NSLog(@"applicationDocumentsDir exists");   // verifies directory exist

NSData *data = [NSData dataWithContentsOfURL:URL];

if (data) {    
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

我不断收到错误

"The operation couldn’t be completed. No such file or directory"
4

2 回答 2

5

尝试

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"myfile.txt"];

 if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
        NSLog(@"applicationDocumentsDir exists");   
于 2011-08-29T17:30:30.597 回答
0

要获取更多信息,您可以使用

writeToFile:选项:错误:

代替

writeToFile:原子地:

但是您需要在执行写入之前在路径中创建所有子目录。像这样:

// if the directory does not exist, create it...
if ( [fileManager fileExistsAtPath:dir_path] == NO ) {
    if ( [fileManager createDirectoryAtPath:dir_path withIntermediateDirectories:NO attributes:NULL error:&error] == NO  ) {
        NSLog(@"createDirectoryAtPath failed %@", error);
    }
}
于 2019-03-07T20:32:47.913 回答