I want to save my application data in text file in documents folder
I am using following way to store but it store single string i want that my data is in array how may store all the contents of array in text files
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString*yourString=#"This is working fine";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"file.txt"];
NSString *stringWithoutSpaces = [yourString stringByReplacingOccurrencesOfString:#" " withString:#""];
[stringWithoutSpaces writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
My Array is like Following
DataController *coffeeObj = [appDelegate.coffeeArray objectAtIndex:indexPath.row];
cell.resturantLocationLabel.text=coffeeObj.resturantLocation;
cell.foodQualityRatingLabel.text=coffeeObj.foodQualityRating;
cell.foodPresentationRatingLabel.text=coffeeObj.foodPresentationRating;
cell.waiterRatingLabel.text=coffeeObj.waiterRating;
cell.ambienceRatingLabel.text=coffeeObj.ambienceRating;
cell.overallRatingLabel.text=coffeeObj.overallRating;
cell.commentsLabel.text=coffeeObj.comments;
cell.emailAddressLabel.text=coffeeObj.emailAddress;
cell.addtoMailingListLabel.text=coffeeObj.addtoMailingList;
NSString*test=coffeeObj.comments;
add your complete array data in NSMutableString and then store in text file.
// Here you set your text.
NSString *yourAppendingText = #"yourAppendingText";
// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:#"file.txt"];
// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one if it is
if(textFromFile){
NSLog(#"appending");
NSString *textToFile = [textFromFile stringByAppendingString:[NSString stringWithFormat:#" %#",yourAppendingText]];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
else{
NSLog(#"not appending");
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
Related
in my application, i have placed an empty
myFile.txt
when i have internet connection , i get json data from internet and save the json string in it with following code
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
[myString writeToFile:filePath automatically:YES encoding:NSUTF... error:nil];
//now while retrieving it when no internet connection
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"txt"];
NSString *myString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF.. error:nil];
now myString returns with #""... why i am not been able to write data?
Best Regards
Whatever you want to do is not possible (or at least strongly discouraged) to update files in the app bundle.
If you’re downloading files and want to store them on the device you should use the Documents directory. You can get the path to this directory with:
- (NSString *)getDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
First check weather the contents are getting written to file. You can view the file in xcode.
What i suggest is when you run the app create this empty file. Then you can Read and write to that file easily.
Try Using Below code:
NSError* error = nil;
NSString* jsonFileName = [NSString stringWithFormat:#"myfile"];
NSString* jsonPath = [[NSBundle mainBundle] pathForResource:jsonFileName
ofType:#"txt"];
NSString* jsonString = [NSString stringWithContentsOfFile:jsonPath
encoding:NSUTF8StringEncoding error:&error];
Documents directory:
Write to file
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\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
Display content:
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];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//NSString *csvString = #"S.No,Task,Date,Time";
//NSArray *csvArray=[csvString componentsSeparatedByString:#","];
// Create .csv file and save in Documents Directory.
NSArray *csvArray =[[NSArray alloc]initWithObjects:#"SNo",#"Task",#"Date",#"Time",nil];
//create instance of NSFileManager
// NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Document Dir: %#",documentsDirectory);
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.csv", #"userdata"]]; //add our file to the path
// [fileManager createFileAtPath:fullPath contents:[csvString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; //finally save the path (file)
CHCSVWriter * csvWriter = [[CHCSVWriter alloc] initWithCSVFile:fullPath atomic:NO];
NSInteger numberOfColumns = 4;
for (NSInteger currentIndex = 0; currentIndex < [csvArray count]; currentIndex++) {
id field = [csvArray objectAtIndex:currentIndex];
[csvWriter writeField:field];
if ((currentIndex % numberOfColumns) == (numberOfColumns - 1)) {
[csvWriter writeLine];
}
}
[csvWriter release];
CSV file basically use for making a back up of iphone contacts and it is an Excel file why do you want to make CSV file and if you want, then you have to make an array according to your CSV and for this you have to do study.... well here is code for writing a text in CSV file and save it to in documents directory....
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *FileName = [NSString stringWithFormat:#"%#/File.csv", documentsDirectory];
NSString *Content = [[NSString alloc] initWithFormat:#"%#", stringForCsv];
//stringForCsv is your string which you want to write in file.
[Content writeToFile:FileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
Thank You!
i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];
how to write a xml data in to plist file in iphone? i am using this code
` i m use this code
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *thexml=[[NSString alloc] initWithBytes:[webdata mutableBytes] length:[webdata length] encoding:NSASCIIStringEncoding];
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 *path = [[NSBundle mainBundle] pathForResource:#"mySettings" ofType:#"plist"];
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.plist",
documentsDirectory];
//create content - four lines of text
//NSString *content = #"One\nTwo\nThree\nFour\nFive";
NSString *content =thexml;
NSLog(#"%#",thexml);
//save content to the documents directory
[content writeToFile:fileName
atomically:YES
encoding:NSStringEncodingConversionAllowLossy
error:nil];
[self writePlist:1 fileName:thexml];
[thexml release];
[connection release];`
but i m see the plist file that display a file is a curuupted .?? pls give me a solution ....
thanks in advance
I need to put separate lines into a file, but it seems that it's not supported by
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"myFile"];
[dataString writeToFile:appFile atomically:YES];
It does put a string to a file but it overwrites previous one.
Any suggestions?
To append data to an existing file, create an NSFileHandle instance for that file, then call -seekToEndOfFile and finally -writeData:. You'll have to convert your string into an NSData object yourself (with the correct encoding). And don't forget to close the file handle when you're finished.
The easier, but also less efficient way, is to read the existing file contents into a string, then append the new text to that string and write everything out to disk again. I wouldn't do that in a loop that executes 2000 times, though.
Thanks Ole! That's what I've been looking for.
Some sample code for the others:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"nameOfAFile"];
//clearing or creating (NSFileHande doesn't support creating a file it seems)
NSString *nothing = #""; //remember it's CLEARING! so get rid of it - if you want keep data
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];
//appending data do the end of file
NSString *dataString = #"All the stuff you want to add to the end of file";
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];
//memory and leaks
[fh closeFile];
[fh release];
[dataString release];