Objective-C 创建一个带有字符串的文本文件

Objective-C creating a text file with a string(Objective-C 创建一个带有字符串的文本文件)

本文介绍了Objective-C 创建一个带有字符串的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的桌面上创建一个包含字符串内容的文本文件.我不确定我是否做得对,我没有收到错误,但它也不起作用......

I'm trying to create a text file with the contents of a string to my desktop. I'm not sure if I'm doing it right, I don't get errors but it doesn't work either...

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: @"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];

推荐答案

//Method writes a string to a text file
-(void) writeToTextFile{
    //get the documents directory:
    NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                                  documentsDirectory];
    //create content - four lines of text
    NSString *content = @"One
Two
Three
Four
Five";
    //save content to the documents directory
    [content writeToFile:fileName 
                     atomically:NO 
                           encoding:NSStringEncodingConversionAllowLossy 
                                  error:nil];

}

这篇关于Objective-C 创建一个带有字符串的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Objective-C 创建一个带有字符串的文本文件

基础教程推荐