簡體   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];
    }
}

我只是想創建一個文本文件,它總是給我“它還沒有在這里”代碼有問題嗎?

您尚未創建文件,僅創建了文件路徑:您需要將文件寫入該路徑。

   //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警告:

注意:不建議嘗試基於文件系統的當前狀態或文件系統上的特定文件來斷言行為。 這樣做可能會導致奇怪的行為或比賽條件。 嘗試執行某個操作(例如加載文件或創建目錄),檢查錯誤並優雅地處理這些錯誤比嘗試提前確定該操作是否成功要好得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM