【问题标题】:NSFileManager or NSTask moving filetypesNSFileManager 或 NSTask 移动文件类型
【发布时间】:2014-03-29 17:17:09
【问题描述】:

我一直在努力寻找解决方案来完成本应非常简单的任务。我需要将某种类型的文件(在这种情况下为所有 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];

        }       
    }
}

失败 - 文件已复制 = zeroooo

- (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];

}

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

【问题讨论】:

    标签: objective-c macos cocoa nsfilemanager nstask


    【解决方案1】:

    在第一种情况下,您没有在复制调用中使用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。由于您没有使用外壳,因此您不需要这样做。 (另外,如果您确实需要转义它,它不应该是 arguments 数组的单独元素。它应该与分号在同一个元素中,例如 @"\\;"。)

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

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

    【讨论】:

    • 谢谢肯,很有帮助:)
    猜你喜欢
    • 2014-12-10
    • 1970-01-01
    • 2023-03-29
    • 2014-06-26
    • 2013-10-03
    • 2012-12-08
    • 2011-11-29
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多