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

Posted

技术标签:

【中文标题】如何处理带空格的文件名?【英文标题】:How do I handle file names with spaces? 【发布时间】:2014-10-05 08:46:26 【问题描述】:

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

代码从这里开始:

[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");
        

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

【问题讨论】:

【参考方案1】:

您将 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:

重要提示:成功或失败由 方法。虽然 Cocoa 方法间接返回错误对象 Cocoa 错误域保证返回这样的对象,如果 方法直接返回 nil 或 NO 表示失败,你应该 在尝试之前总是检查返回值是 nil 还是 NO 对 NSError 对象做任何事情。

【讨论】:

【参考方案2】:

您似乎正在尝试手动将 URL 转换为文件路径。请改用 fileSystemRepresentation。

【讨论】:

fileSystemRepresentation 是一个 NSString 方法并返回一个 C 字符串,该字符串可用于“低级”函数,如 open()rename()

以上是关于如何处理带空格的文件名?的主要内容,如果未能解决你的问题,请参考以下文章

c++ 文件操作 如何处理空格的

sql导入数据时总是报错,详见下图,请大神指导如何处理?文件格式改过多个版本,也没有空格或符号

linux shell 中 如何处理空格的路径?

VB调用SHELL,参数路径有空格如何处理?

VB调用SHELL,参数路径有空格如何处理?

python正则如何处理NULL?