gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:11:43 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com