标签:
var fileManager = NSFileManager()
// 取得文件夹的路径,注意:末尾加/与不加同样,推荐末尾加/ // Define folderPath var filePath = "/Users/Star/desktop/PathName/"
// 获得文件夹下文件名称集合。注:此处获得文件名称,而不是全部路径 // Get all filenames array in the folder, warning: only filename and not full path var oldFileNamesArray = fileManager.contentsOfDirectoryAtPath(filePath, error: nil) as [String] for oldFileName in oldFileNamesArray{
// 取得旧名称的全部路径 // Append to file full name var oldFilePathName = filePath + oldFileName
// 取得需要修改的字的所在范围 // Get range of replace string var rangeString = oldFileName.rangeOfString("OldName", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil); if rangeString == nil { continue }
// Swift中的String 是引用类型 // 不能直接修改 for in 遍历的元素 // Define a new string Becauce we cannot direct replacing the for in circulation element var newFileName = oldFileName
// 替换掉Old字符串 // replaced to NewName newFileName.replaceRange(rangeString!, with: "NewName") // 取得新名词的全部路径 // Get the new full path var newFilePathName = filePath + newFileName // 执行文件移动函数,此函数能实现文件名称修改 // Execute the function "moveItemAtPath" with moving the file // The function can replace "rename" // return execution result if fileManager.moveItemAtPath(oldFilePathName, toPath: newFilePathName, error: nil){ println("成功 successful") } else{ println("失败 failed") } }
标签:
原文地址:http://www.cnblogs.com/YHStar/p/4306784.html