I am using the following code in iPhone to write a string into the file that is stored in my iPhone Project Resource Folder. When i try to read its reading the data successfully but when i try to write its not writing the file although its aloso not giving me any error.
this is my code:
NSString *myString; //Assuume the string you want to write is this
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
[myString writeToFile:path atomically:YES];
Please can anybody guide.
- (void) testStringReadWrite {
NSString *myString = #"abcd efgh";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
CFShow(path);
NSError *error = nil;
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#",error);
}
NSString *readString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", error);
} else {
CFShow(readString);
}
}
The writeToFile:atomically: has been depredecated in iOS 2.0. Use writeToFile:atomically:encoding:error: instead. You should check the content of the string, for example by NSLog() function. Inappropriate initialization can cause a failure.
NSLog(#"%#", myString);
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Just my two cents, coming from OS X, I am used to calling writeToURL() instead of writeToFile(). Turns out, writeToFile() is the one that worked for iOS.
Related
I want to read and print the file's content which downloaded from dropbox but my "readFile" method prints null. I am sure the file is downloaded successfully.
-(void)download
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", #"File.txt"]];
[[self restClient] loadFile:#"/File.txt" intoPath:filePath];
}
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
contentType:(NSString*)contentType metadata:(DBMetadata*)metadata {
[self readFile:#"File.txt"];
NSLog(#"File loaded into path: %#", localPath);
}
-(void)readFile:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileNameData=[NSString stringWithFormat:#"%#",fileName];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileNameData];
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSError *error;
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", error);
}
and this is output:
---------******** CONTENT OF THE DOWNLOADED FILE *********------------(null)
I updated my code for capture erorr and I am getting this error from stringWithContentsOfFile:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x1669c2b0 {NSFilePath=/var/mobile/Applications/11B10727-E372-1147-26BD-1D24S60B8E54/Documents/File.txt, NSStringEncoding=4} 2013-08-05 22:06:03.229 DBApp[496:60b]
It looks like your code is reading a file called "File.txt" rather than the actual file that was downloaded from Dropbox. Am I missing something?
EDIT
Based on the comments below, it looks like the error is 261, related to string encoding. You might want to try a different encoding or ensure that the text file is encoded the way you expect it to be.
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];
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];
}
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];
i am new developer in iphone application. i would like write a content in xml file for that, i have created xml file and write tags with element, attribute and value with some data in that xml as follows.
-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName NodeName:(NSString *)Node{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *fileExtension = [NSString stringWithFormat:#"%#%#",fileName,#".xml"];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileExtension];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists) {
NSError *error = nil;
NSString *docStr;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists)
{
NSLog(#"file exist in document");
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
XMLString = [[NSMutableString alloc]initWithString:docStr];
[self XMLString];
NSLog(#"data%#",XMLString);
}
}
// [XMLString insertString:data atIndex:index];
[XMLString appendFormat:#"<%#>%#</%#> \n",Node,data,Node];
BOOL success = [XMLString writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
else {
NSLog(#"File write is successful");
}
}
}
i want add new tag with new elements,new attributes,etc.,if i enter element at the place of tag it is modifying with previous tag .
here how can i append the new tag to previous appended tags
please any body could help me
Thanks in advance
As a suggestion, you can use APXML to create XML documents it is very simple and easy to use. This post can guide you further.