【问题标题】:NSFileManager moving a file shows errorNSFileManager 移动文件显示错误
【发布时间】:2014-12-10 01:13:36
【问题描述】:

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

我在 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"}

帮我解决我的问题

【问题讨论】:

  • 那么,当您使用两种不同的方式获取路径时,您期望什么?
  • 您不能一开始就使用“文档/...”。使用this
  • @borrrden 帮帮我,我是文件管理器的新手
  • 执行与第一段代码相同的操作以再次获取目录
  • 能发一下代码吗

标签: ios nsfilemanager


【解决方案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]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2016-03-31
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多