简体   繁体   English

IOS中的NSFileManager

[英]NSFileManager in IOS

- (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 ?? 我只是想创建一个文本文件,它总是给我“它还没有在这里”代码有问题吗?

You haven't created a file, you have only created a file path: you need to write a file to that path. 您尚未创建文件,仅创建了文件路径:您需要将文件写入该路径。

   //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]

But watch out - file existence tests come with a warning from Apple: 但请注意-文件存在性测试附带Apple警告:

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. 注意:不建议尝试基于文件系统的当前状态或文件系统上的特定文件来断言行为。 Doing so can cause odd behavior or race conditions. 这样做可能会导致奇怪的行为或比赛条件。 It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. 尝试执行某个操作(例如加载文件或创建目录),检查错误并优雅地处理这些错误比尝试提前确定该操作是否成功要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM