0
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSFileManager * fileManager =[[NSFileManager alloc]init];
    NSArray  *Apath=[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    NSString *FilePath=[[Apath objectAtIndex:0] absoluteString];
    NSString *TEST =[FilePath stringByAppendingPathComponent:@"test10.txt"];
    BOOL flage =[[NSFileManager  defaultManager] fileExistsAtPath:TEST];

    if (flage)
    {
        NSLog(@"It's exist ");
    }
    else
    {
        NSLog(@"It is not here yet ");
        NSData * data =[[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"www.google.com"]];
        [data writeToFile:TEST atomically:YES];
    }
}

I'm just trying to create a text file , it always give me "It is not here yet" Anything wrong with the code ??

4

1 回答 1

1

您还没有创建文件,您只是创建了一个文件路径:您需要将文件写入该路径。

   //after these lines ... (I've improved your variable names) 
NSArray  *paths=[fileManager URLsForDirectory:NSDocumentDirectory 
                                    inDomains:NSUserDomainMask];
NSString *filePath=[[paths objectAtIndex:0] absoluteString];
filePath =[filePath stringByAppendingPathComponent:@"test10.txt"];


   //try this
NSString* fileContent = @"some text to save in a file";
BOOL success = [fileContent writeToFile:filePath 
              atomically:YES 
                encoding:NSUTF8StringEncoding 
                   error:nil]

但请注意 - 文件存在测试伴随着来自 Apple 的警告:

注意:不建议尝试基于文件系统的当前状态或文件系统上的特定文件来判断行为。这样做可能会导致奇怪的行为或竞争条件。尝试操作(例如加载文件或创建目录)、检查错误并优雅地处理这些错误比尝试提前确定操作是否成功要好得多。

于 2013-10-20T13:32:00.667 回答