这可能是基于上述问题:
Read and write data from text file
我想做的是,如果连接了某种类型的可移动卷,可以选择直接在驱动器上写入文件,如果可能的话,可以在该驱动器的某个子文件夹中写入文件。
let fileManager = FileManager.default
var Extension: String = "txt"
let FileName: String = "TestFileName"
var DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(FileName).appendingPathExtension(Extension)
print("FilePath: \(fileURL.path)")
let DocumentIntro = "This text will be on the text file\n"
do {
// Write to the file
try DocumentIntro.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
var FileContents = "" // Used to store the file contents
do {
// Read the file contents
FileContents = try String(contentsOf: fileURL)
} catch let error as NSError
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}