kemdo
kemdo

Reputation: 1459

How to create a .txt file programmatically on iOS

I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.

Upvotes: 5

Views: 21149

Answers (2)

Mayank Patel
Mayank Patel

Reputation: 3908

I hope this help's you

  -(void)writeToTextFile{

    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:@"%@/filename.txt", 
                                                  documentsDirectory];
    NSString *content = @"This is Demo";
    [content writeToFile:fileName 
                     atomically:NO 
                           encoding:NSStringEncodingConversionAllowLossy 
                                  error:nil];

   }

 -(void)ShowContentlist{

    NSArray *paths = NSSearchPathForDirectoriesInDomains
                    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fileName = [NSString stringWithFormat:@"%@/filename.txt", 
                                                  documentsDirectory];
    NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                  usedEncoding:nil
                                                         error:nil];
    [content release];

 }

Upvotes: 5

rebello95
rebello95

Reputation: 8576

Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.

NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

And to retrieve the text file:

NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@", str);

Upvotes: 19

Related Questions