簡體   English   中英

修改目錄中的現有文件,應該替換它(iPhone)

[英]Modify an existing file in directory, with ought replacing it (iPhone)

在我的應用程序中,每次用戶創建新組時,都會創建此代碼(JSON):

{"group a":"0864797073"} 

...然后代碼保存在名為groups.txt的文件的目錄中

...但是當用戶創建另一個組時,我希望以這種方式修改文件:

{"group a":"0864797073"} 
{"group b":"0864797073"} 

...接着...

{"group a":"0864797073"} 
{"group b":"0864797073"} 
{"group c":"0864797073"}

...所以添加一個新行,而不是替換文件。

我怎樣才能做到這一點??

先謝謝您的幫助。

編輯2:

NSString * destDir = [NSString stringWithFormat:@“/ Apps / Quick Homework&business /%@ /”,namegroup.text];

    NSString *filename5 = namegroup.text;
    NSString *filename6 = @"group";


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *groupPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", filename6]];

    NSMutableArray *titles = [NSMutableArray array];
    [titles addObject:filename5];

    NSMutableArray *keys = [NSMutableArray array];
    [keys addObject:filename6];

    NSDictionary *dict = [NSDictionary dictionaryWithObjects:titles forKeys:keys];

    NSString *jsonString = [dict JSONRepresentation];
    NSData *jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding];

    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:groupPath];
    [myHandle seekToEndOfFile];
    [myHandle writeData:jsonData];
    [myHandle closeFile];

    [jsonData writeToFile: groupPath atomically: YES];

    [[self restClient] uploadFile:filename6 toPath:destDir
                    withParentRev:nil fromPath:groupPath];

如果您只想在現有文件的末尾添加一行,則可以使用以下代碼。

NSData *newGroupData = [newGroupString dataUsingEncoding:NSUTF8StringEncoding];

NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:newGroupData];
[myHandle closeFile];

您可以newGroupString設置newGroupStringfilePath的值

您執行以下操作

  • 閱讀舊文件的內容
  • 將新行附加到讀取內容,現在您有一個包含舊文件+用戶添加的新行的集合
  • 將集合寫入文件,這將寫入所有舊內容+新行

暫無
暫無

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

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