Swift 3写入文本文件

时间:2017-12-06 04:23:06

标签: ios swift

在我的应用程序中,我试图将数据添加到名为saveURL.txt的程序的文档目录中的文本文件中,以便以后可以调用和解析它。我的代码是

let fileName = "saveURL"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")

let writeString = "Write this text to the fileURL as text in iOS using Swift"
do {
    // Write to the file
    try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
    print("past try writeString.write")
} catch let error as NSError {
    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}

var readString = "" // Used to store the file contents
do {
    // Read the file contents
    readString = try String(contentsOf: fileURL)
} catch let error as NSError {
    print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)")

控制台中显示的输出是

  

FilePath:/ Users / mike / Library / Developer / CoreSimulator / Devices / 752A5025-0AA0-4BE1-B70F-644A904F2D8A / data / Containers / Data / Application / 0084AD99-63DB-439F-8427-DDDF161CFAC0 / Documents / saveURL。 TXT
  过去尝试writeString.write
  文件文本:使用Swift

将此文本作为iOS中的文本写入fileURL

哪个显示输出它实际存储,但是当我去检查文件是否实际附加到它时,它仍然是空白的。我已经读到了swift文件只是为了读取而且这样但是我也看到了可以工作但不在我的程序中的示例。

1 个答案:

答案 0 :(得分:1)

以下是文本文件中写入url的代码。

    Calendar cal1 = Calendar.getInstance();
    cal1.set(2015, Calendar.JANUARY, 1);

    Calendar cal2 = Calendar.getInstance();
    cal2.set(2016, Calendar.JANUARY, 1);

    Date date1 = cal1.getTime();
    Date date2 = cal2.getTime();

    //Print -1, negative
    System.out.println(date1.compareTo(date2));

    cal1.set(2017, Calendar.JANUARY, 1);
    date1 = cal1.getTime();
    //Print 1, positive
    System.out.println(date1.compareTo(date2));

    cal1 = cal2;
    date1 = cal1.getTime();
    //Print 0, equal
    System.out.println(date1.compareTo(date2));

希望这会对你有所帮助。