objective-c - NSFileManager 或 NSTask 移动文件类型

标签 objective-c macos cocoa nsfilemanager nstask

我一直在努力寻找解决方案来完成本来应该非常简单的任务。我需要将某种类型的文件(本例中为所有 zip 文件)移动到另一个目录中。我尝试过 NSTask 和 NSFileManager 但结果是空的。我可以一次移动一个,但我想同时一次移动它们。

- (void)copyFilesTo :(NSString*)thisPath {

    NSFileManager *manager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:thisPath];
    NSString *filename = nil;

    while ((filename = [direnum nextObject] )) {

        if ([filename hasSuffix:@".zip"]) {

            [fileManager copyItemAtPath:thisPath toPath:newPath];

        }       
    }
}

失败 - 复制的文件 = 零

- (void)copyFilesMaybe :(NSString*)thisPath {

    newPath = [newPath stringByAppendingPathComponent:fileName];

    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/bin/find"];
    [task waitUntilExit];

    NSArray *arguments;

    arguments = [NSArray arrayWithObjects: thisPath, @"-name", @"*.zip", @"-exec", @"cp", @"-f", @"{}", newPath, @"\\", @";", nil];

    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

}

同样的悲伤结果,没有复制文件。我到底做错了什么?

最佳答案

在第一种情况下,您在复制调用中没有使用filename。您需要通过将 filenamethisPath 组合并尝试复制来构造文件的完整路径。另外,该方法是-copyItemAtPath:toPath:error:。您遗漏了最后一个参数。尝试:

            NSError* error;
            if (![fileManager copyItemAtPath:[thisPath stringByAppendingPathComponent:filename] toPath:newPath error:&error])
                // handle error (at least log error)

在第二种情况下,我认为你的arguments数组是错误的。我不确定为什么它包含 @"\\"。我怀疑是因为在 shell 中你必须用反斜杠 (\;) 转义分号。但是,需要转义分号是因为 shell 会解释它并且不会将其传递给 find。由于您没有使用 shell,因此不需要这样做。 (此外,如果您确实需要转义它,它不应该是参数数组的单独元素。它应该与分号位于同一元素中,例如 @"\\;"。 )

另外,您确定任务已经完成吗?您显示了启动,但没有显示出观察或等待其终止。鉴于您已经为其输出设置了一个管道,您必须从该管道中读取数据,以确保子进程不会在写入时卡住。

我不确定您为什么在启动任务之前调用 -waitUntilExit。不过,这可能是无害的。

关于objective-c - NSFileManager 或 NSTask 移动文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22734221/

相关文章:

objective-c - Xcode - 让单元格在触摸事件后显示新文本,使其展开

objective-c - Cocoa - 使用 setFrame 对 NSWindow 进行动画处理

php - Mac OS X + PHP : Cannot redeclare class testing

javascript - 为什么在主进程和渲染进程中调用的 window.maximize() 与 macos 上的动画不同?

objective-c - 如何轻松重定向 NSTextView 中的控制台输出?

iphone - 如何将 nil-terminated 字符串列表传递给 Objective-C 函数?

ios - SCLAertView 正在等待 API,但没有持续时间

html - Mac 和 Windows 浏览器中的不同 CSS

xcode - Interface Builder 中带有自动 NSNumberFormatter 的 NSTextField

macos - 操作系统状态栏上的 "disabled"图标规范