【问题标题】:Append new string to txt file in swift 2在swift 2中将新字符串附加到txt文件
【发布时间】:2016-08-12 16:25:04
【问题描述】:

我以前用 java 编写代码,但现在我想使用 swift 2 将我的应用程序移动到 iOS。 所以我想要一种将新行中的文本附加到应用文档中现有 txt 文件的方法。

我搜索并尝试了很多方法,但都覆盖到新的txt文件

在java中我使用了这个方法

PrintWriter out=null;
        try {
            out=new PrintWriter(new FileWriter("file.txt",true));

                    out.println("some txt"}


                out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

【问题讨论】:

    标签: ios swift2 nsfilehandle


    【解决方案1】:

    您可以使用以下方法将字符串附加到文件中

    func writeToFile(content: String, fileName: String) {
    
        let contentToAppend = content+"\n"
        let filePath = NSHomeDirectory() + "/Documents/" + fileName
    
        //Check if file exists
        if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
            //Append to file
            fileHandle.seekToEndOfFile()
            fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
        }
        else {
            //Create new file
            do {
                try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
            } catch {
                print("Error creating \(filePath)")
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我认为你必须使用 NSFileHandle

        let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
        let fileurl =  dir.URLByAppendingPathComponent("file.txt")
      
        let string = "\(NSDate())\n"
        let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
      
        if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
              var error:NSError?
              if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {
                  fileHandle.seekToEndOfFile()
                  fileHandle.writeData(data)
                  fileHandle.closeFile()
              }
              else {
                  println("Can't open fileHandle \(error)")
              }
        }
        else {
              var error:NSError?
              if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &error) {
                  println("Can't write \(error)")
              }
        }
      

      【讨论】:

        猜你喜欢
        • 2014-11-19
        • 1970-01-01
        • 2013-08-02
        • 1970-01-01
        • 2014-11-18
        • 2016-03-02
        • 2018-02-28
        • 1970-01-01
        • 2022-01-18
        相关资源
        最近更新 更多