gpt4 book ai didi

objective-c - 如何处理带空格的文件名?

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

我使用下面的代码来复制在文件浏览器中选择的文件,并将其复制到具有不同名称的临时目录中。但是,当我选择其中包含空格的文件时,程序会抛出错误,指出找不到指定的精细路径。我尝试过使用转义方法,但它们也不起作用。还有其他方法可以处理带空格的文件名吗?

代码从这里开始:

[openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) {
[openPanel close];

if (result == NSFileHandlingPanelOKButton) {
myString = [self randomStringWithLength:7];
NSString *filePath = [[[openPanel URLs] objectAtIndex:0] absoluteString];

NSLog(@"%@", filePath);

NSString *strTemp = [self extractString:filePath toLookFor:@"//" skipForwardX:2 toStopBefore:@".png"];
NSLog(@"%@",strTemp);
NSString *realThing = [strTemp stringByReplacingOccurrencesOfString:@"%20" withString:@"\\ "];
//strTemp = [strTemp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", realThing);

NSString* fullPath = [NSString stringWithFormat:@"/tmp/%@.png", myString];
NSLog(fullPath);


NSError *error = nil;
[[NSFileManager defaultManager] copyItemAtPath:realThing toPath:fullPath error:&error];
if(error) {
NSLog(@"Error!!!");
NSLog(@" error => %@ ",error);
}
else {
NSLog(@"Saved to temp directory");
}

有人有这方面的经验吗?谢谢

最佳答案

将 URL 转换为路径过于复杂且容易出错。只需使用 path 方法:

NSString *filePath = [[[openPanel URLs] objectAtIndex:0] path];

或者,使用 copyItemAtURL:... 而不是 copyItemAtPath:...

您还应该检查 copyItemAtPath:...返回值作为指示器失败:

if (![[NSFileManager defaultManager] copyItemAtPath:filePath toPath:fullPath error:&error]) {
NSLog(@" error => %@ ",error);
}

比较 Handling Error Objects Returned From Methods :

Important: Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

关于objective-c - 如何处理带空格的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201047/

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