I searched a lot and didn't find the solution.
Here is my code:
NSString* path = [[NSBundle mainBundle] pathForResource:#"dicpart"
ofType:#"rtf"];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error) NSLog(#"error: %#", error);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/file.txt", documentsDirectory];
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:&error];
if (error) NSLog(#"error: %#", error);
What I'm doing:
Get the file (http://take.ms/Xo3Cx, it contains Cyrillic and some special latin symbols)
Read the string from this
Save the file back immediately with no modification
Problem:
Cyrillic and special latin symbols become to be a rubbish.
I suppose I should do sort of decoding in order to get real symbols in the result file. What should I do to achieve this?
The problem was solved by changing the unput file format to .txt.
Related
I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:#"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:#"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];
NSLog(#"%#",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:NULL];
iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
NSLog(#"error: %#", error)
}
I'm trying to write a simple string to file, using the following code:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
NSString *content = #"Test Content";
NSError *error = nil;
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(#"Error %# %#", fileName, error);
But the file is'nt written and error is null.
I'm running the code in the iOS Simulator and expect the file to be written to a location like: /Users/user/Library/Developer/CoreSimulator/Devices/85DDC17D-A771-40D9-99BE-71FF6B60D2DF/data/Containers/Data/Application/BD30A945-25DB-4ECE-B7F7-E9C20C6691C7/Documents/textfile.txt (the Path of fileName from NSLog).
As #rckoenes pointed out it was an error in the rest of my code. I have a function that deletes all files in "documents", i just didn't remember that i had this function and because of the length of the code (>5000 lines) it was hard to find. Thank you all!
working with URLs is a bit reliable way, so I would re-work your idea slightly like e.g. this:
NSURL *_documentFolder = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *_fileURL = [_documentFolder URLByAppendingPathComponent:#"textFile.txt"];
NSError *_error = nil;
BOOL _success = [#"hello!" writeToURL:_fileURL atomically:TRUE encoding:NSUTF8StringEncoding error:&_error];
that works perfectly on simulator and on real device too, and the file textFile.txt will have the content hello!.
NOTE: if the _success value is FALSE, you can get more information about the reason via a the _error, even if you'd just log it to the debug-console. I have not isolated the NSString in my example, but you can replace it with your own instance.
please check below code:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:#"textfile.txt"];
NSString *temp = [[NSString alloc] initWithString:#"Test Content"];
[temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
I'm having a big trouble. I'd like to concatenate data of multiple textfiles into another textfiles. But I cannot. can you help me ? Many thanks
Read each file one by one,
NSString *firstFileContent = [NSString stringWithContentsOfFile:<your file path>
encoding:NSASCIIStringEncoding
error:nil];
//Similarly read other files, and store them in secondFileContent and thirdFileContent.
//now concatenate all to form one big string.
NSString *bigString = [NSString stringWithFormat:#"-First File- \n%# \n-Second File- \n%#\n-Third File-\n%#",firstFileContent, secondFileContent, thirdFileContent];
//write to file, create a new one
[bigString writeToFile:<path to write>
atomically:YES
encoding:NSASCIIStringEncoding
error:nil];
Edit 1 :
As per your comment that your file is in DocumentDirectory use this code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:<your file name>];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
First load content of file in NSString and use following code:
NSString *strConcatenate = [NSString stringWithFormat:#"%# %# %#", textfiles1, textfiles2, textfiles3];
NSLog(#"%#", strConcatenate);
You just have to load the content of the files into NSMutableString and concatenate them :
NSMutableString *myString = #"Content of the first file";
NSString *test = [myString stringByAppendingString:#" content of the second file"];
You need to read the text files in from the bundle and then append them, once you have that then write it back out. I wrote this example and I hope you can learn from it.
NSMutableString *mutableString = [[NSMutableString alloc] init];
NSArray *textFiles = #[ #"textfile1", #"textfile2", #"textfile3" ];
for (NSString *textFileName in textFiles) {
NSString *path = [[NSBundle mainBundle] pathForResource:textFileName
ofType:#"txt"];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (content) {
[mutableString appendFormat:#"%#\n", content];
} else {
NSLog(#"%#", error.localizedDescription);
}
}
NSLog(#"%#", mutableString);
NSError *error = nil;
BOOL result = [mutableString writeToFile:#"concatenated_file.txt" atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!result) {
NSLog(#"%#", error.localizedDescription);
}
I have an editable uitextview in which the user types in Russian or English. I then save this text as a .txt file in the files directory, and read it later.
Here is the portion to save the text
-(IBAction)saveText:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"testing.txt"];
[self.textBox.text writeToFile:path atomically:YES];
NSLog(path);
}
There is a separate button to display this text in a popover:
-(IBAction)readText:(id)sender{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"testing.txt"];
NSError *error = nil;
myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"myText: %#", myText);
self.textBox.text= myText;
}
with this declaration in the .h file
NSString *myText;
it works fine if I only type English, but if I type Russian characters then nothing saves/displays.
So, say I type "hello" it works, but ifI then type " some Russian phrase " to append self.textBox.text it doesn't work.
How can I make this Russian (or UTF8/charcode) compatible?
writeToFile:atomically: is deprecated and writes the string in the default encoding
(whatever that is, probably MacRoman). Better use
[self.textBox.text writeToFile:path
atomically:NO
encoding:NSUTF8StringEncoding
error:&error];
to write the string UTF-8 encoded.
How would I go about creating a new text file in my program so that I can write content to it? I already understand how to write content but I haven't been able to find anything (anything easy to understand) on the subject.
Use this method:
+ (id)stringWithContentsOfFile:(NSString *)path
usedEncoding:(NSStringEncoding *)enc
error:(NSError **)error
An example:
NSString* path = [[NSBundle mainBundle] pathForResource:#"Example"
ofType:#"txt"];
NSError *error = nil;
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if(error)
{
NSLog(#"ERROR while loading from file: %#", error);
}
Write to a file works this way:
Use this method:
- (BOOL)writeToFile:(NSString *)path
atomically:(BOOL)useAuxiliaryFile
encoding:(NSStringEncoding)enc
error:(NSError **)error
Example:
[text writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:nil];
Mistake:
Can't just write to bundle path. Need to copy it to Documents Directory.
-(void)copyBundleToDocuments
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"Example.txt"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"Example.txt"];
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success)
{
[text writeToFile:documentPlistPath atomically:NO encoding:NSUTF8StringEncoding error:nil];
}
}
Your question is so broad one could drive a truck (or lorry, in UK English) through the middle of it.
But in general, you could add a UITextView to one of your view controllers.
And when you are ready to save, you could take the contents of the text view (which is a NSString), and save it to a file via the NSString writeToFile methods.
And you can load the text view later on via NSString's "initFromFile" method, as long as you know the path to that file.
Here are other questions that people have asked that may help you out.
You can use UITextView to write text
save the file using
[txtView.text writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
Get the TextFile content using
NSString* content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:NULL];