【问题标题】:Cleaning .txt in Documents folder清理 Documents 文件夹中的 .txt
【发布时间】:2013-02-03 16:24:32
【问题描述】:

我正在将 .txt 文件添加到 Documents 文件夹,以使用此处建立的解决方案存储一些数据: Read Text File in Document Folder - Iphone SDK

所以现在我可以成功地写入和读取该文件中的文本,但我还需要采取行动清除该文件中的所有文本以使其绝对为空。有可能吗?

【问题讨论】:

  • 嗯,最简单的方法是删除文件,然后创建一个具有相同名称的新文件。你可以使用this tutorial 来学习如何做到这一点。

标签: ios objective-c xcode text nsuserdefaults


【解决方案1】:

在一行中,应该这样做:

[[NSData data] writeToFile: pathToFile atomically: YES];

【讨论】:

    【解决方案2】:

    这将循环所有文件 - 在文档目录 - 后缀为“txt”并删除其内容:

    NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSArray *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    for (NSString *fileName in arr) {
        if ([fileName hasSuffix:@".txt"])
        {
            [@"" writeToFile:[path stringByAppendingPathComponent:fileName] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
    }
    

    【讨论】:

    • 从 iOS 8 开始,不要使用它来获取 Documents 文件夹。它不再只是在“主”目录之外。
    猜你喜欢
    • 1970-01-01
    • 2020-09-29
    • 2010-11-09
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多