【问题标题】:Copy folder to a non-empty directory将文件夹复制到非空目录
【发布时间】:2018-06-11 10:31:38
【问题描述】:

是否可以在不先删除目标文件夹的内容的情况下将文件夹复制到非空目标? 我目前的实现如下

var folderObject = NSFileManager.defaultManager();
folderObject.removeItemAtPath_error(toPath, nil);
folderObject.copyItemAtPath_toPath_error(fromPath, toPath, nil));

我需要实现的是用源文件夹的内容覆盖目标文件夹的内容。

【问题讨论】:

  • 你应该edit你的问题来展示removeItemAtPath_errorcopyItemAtPath_toPath_error的实现,因为它们不是内置函数。顺便说一句,这是 Swift,不要在行尾使用 ; 并符合 Swift 命名约定,函数名称为 lowerCamelCase。您还应该使用参数标签,而不是将它们包含在函数名称中。因此,例如将removeItemAtPath_error 更改为removeItem(at path:String,error:Error?),其他函数也一样。
  • toPath 是目标文件夹,fromPath 是源文件夹吗?
  • @DávidPásztor Swift 标签由 trungduc 添加。该问题被标记为 Objective-C。 removeItemAtPath:error:copyItemAtPath:toPath:error:NSFileManager 方法。 @Vandaan 这是 Python 吗?
  • @Willeke 问题中的代码在任何一种情况下都没有任何意义。该语法是 Swift 语法,但函数签名与 Swift 中内置方法的签名不匹配。从语法上看,标签编辑似乎是一个有效的决定,但这段代码对于从 Swift 或 Objective-C 调用内置的 NSFileManager 方法无效。
  • @DávidPásztor 看看PyObjC

标签: file-handling nsfilemanager sketchapp cocoascript


【解决方案1】:

调用removeItemAtPath_error删除目标目录,copyItemAtPath_toPath_error创建一个与删除目录同名的目录,因此它是空的。

附带说明一下,NSFileManager 实例的命名有些误导,因为它不是文件夹对象,而是文件管理器实例引用。

如何做到这一点的一个例子(我不熟悉PyObjC,所以这只是为了启发):

# Define paths
var sourcePath = "/my/source/path/"
var targetPath = "/my/target/path/"

# Create reference to file manager
var fileManager = NSFileManager.defaultManager();

# Create array of all file and directory paths inside the source directory
var sourcePaths = fileManager.contentsOfDirectoryAtPath_sourcePath_error(sourcePath, nil); 

# For each source file or directory
for sourcePath in sourcePaths:

  # Copy the file or directory to the target path
  fileManager.copyItemAtPath_toPath_error(sourcePath, targetPath, nil);

我假设这会递归地从源中复制目录并维护目录树。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多