如果文件已经存在,如何增加文件名?

时间:2017-09-06 04:34:07

标签: ios swift

如果文件已经存在,如何增加文件名?这是我正在使用的代码:

let count: Int = 1
var newFileName = ""

let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent("MyDoc.pdf").path!
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
    print("FILE AVAILABLE")
    newFileName =  "MyDoc\(count).pdf"

} else {
    print("FILE NOT AVAILABLE")
}

MyDoc.pdf,MyDoc(1).pdf,MyDoc(5).pdf然后如何增加?

3 个答案:

答案 0 :(得分:1)

在此代码中,您每次都创建MyDoc1.pdf

如果您希望每次都有新的pdf文件,那么您可以获得位置上的文件数(计数)和文件的增量数(计数)+ 1

答案 1 :(得分:1)

Swift 4解决方案:

func copyFile(fromPathString:String, toPathString:String) {

    let myManager = FileManager.default
    let fromPath : URL = URL(fileURLWithPath: fromPathString)
    var toPath = toPathString + fromPath.lastPathComponent
    let filename = (URL(fileURLWithPath: toPath)).lastPathComponent
    let fileExt  = (URL(fileURLWithPath: toPath)).pathExtension
    var fileNameWithoSuffix : String!
    var newFileName : String!
    var counter = 0


    if filename.hasSuffix(fileExt) {
        fileNameWithoSuffix = String(filename.prefix(filename.count - (fileExt.count+1)))
    }

    while myManager.fileExists(atPath: toPath) {
        counter += 1
        newFileName =  "\(fileNameWithoSuffix!)_\(counter).\(fileExt)"
        let newURL = URL(fileURLWithPath:toPathString).appendingPathComponent(newFileName).path
        toPath = newURL
    }

    try! myManager.copyItem(atPath: fromPathString, toPath: toPath)

}

答案 2 :(得分:0)

使用while语句增加计数器,直到找到未采用的文件名:

guard var filePath = url.URLByAppendingPathComponent("MyDoc.pdf").path else {
    // force-unwrapping is not the answer! Handle error
    return
}

let fileManager = NSFileManager.defaultManager()

var counter = 0

while fileManager.fileExistsAtPath(filePath) {
    counter += 1

    newFileName =  "MyDoc(\(counter)).pdf"
    let newURL = url.URLByAppendingPathComponent(newFileName) 

    guard let newPath = newURL.path else {
        // Handle error (shouldn't happen anyway)
        return
    }
    path = newPath // Try again...
}

注意:我没有尝试编译此代码。它可能有一些小错误。