gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:55:24 25 4
gpt4 key购买 nike

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

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 那么如何递增呢?

最佳答案

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)

}

关于ios - 如果文件已经存在,如何增加文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066840/

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