移动文件的NSFileManager显示错误

时间:2014-10-15 04:23:23

标签: ios nsfilemanager

我正在尝试创建两个日志文件,并将第二个文件中的内容替换为第一个文件中的内容。

我在AppDelegate中创建日志的代码

   NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
       logPath3 = [documentsDirectory3 stringByAppendingPathComponent:@"console4.log"];

        if(![[NSFileManager defaultManager] fileExistsAtPath:logPath3])
            [[NSFileManager defaultManager] createFileAtPath:logPath3 contents:[NSData data] attributes:nil];

        NSLog(@"path %@",logPath3);

        freopen([logPath3 cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);

 NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
        logPath2 = [documentsDirectory2 stringByAppendingPathComponent:@"console3.log"];

        if(![[NSFileManager defaultManager] fileExistsAtPath:logPath2])
            [[NSFileManager defaultManager] createFileAtPath:logPath2 contents:[NSData data] attributes:nil];

        NSLog(@"path %@",logPath2);

        freopen([logPath2 cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
        _isFileOneCreated =YES;

移动内容的代码

NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];

    NSError * err;
if ([filemgr moveItemAtPath:
     logPath2 toPath:
   logPath3 error: &err])
    NSLog (@"Day 3 Move successful");
else
    NSLog (@"Day 3 Move failed  %@",[err localizedDescription]);

但我收到错误516。

   (Cocoa error 516.)" UserInfo=0x16dba220    {NSSourceFilePathErrorKey=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console3.log, NSUserStringVariant=(
Move
), NSFilePath=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console3.log, NSDestinationFilePath=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console4.log, NSUnderlyingError=0x16da63f0 "The operation couldn’t be completed. File exists"}

帮我解决问题

1 个答案:

答案 0 :(得分:1)

moveItemAtPath 不允许您覆盖具有相同名称的文件。请参阅此Question Thread

您需要做的只是删除目标位置的文件,然后再覆盖新文件。使用以下代码。这样做会有所帮助,但我建议你采取预防措施备份你的文件以防万一 move 因某些未知原因而无法工作。

NSFileManager *filemgr = [NSFileManager defaultManager];   
NSError * err;  
[filemgr removeItemAtPath:logPath3 error:&err];  
if ([filemgr moveItemAtPath:logPath3 toPath:logPath2 error: &err])   
   NSLog (@"Day 3 Move successful");  
else   
   NSLog (@"Day 3 Move failed  %@",[err localizedDescription]);