I coded a method to load a txt file into an array. However, I'm not really happy with it as it looks terribly cumbersome to my beginner's eyes (I'm sure I don't need 50% of my code) and I am somehow wondering how I can specify the exact format of my txt file, e.g. NSUTF8StringEncoding.
Here is my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Sample.txt"];
if (filePath) { // check if file exists - if so load it:
NSString *myText = [NSString stringWithContentsOfFile:filePath];
if (myText) {textView.text=myText;}
}
For any suggestions of how to polish this up and specify the right format, I'd be very grateful.
Try the following, assuming your file is in your bundle:
NSString * filePath = [[NSBundle mainBundle] pathForResource:#"Sample" ofType:#"txt"];
NSError * error = nil;
NSString * contentsOfFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
Into an array? You mean into a string, since is exactly what you're doing...
However, your code looks not bad, and most of it is just to grab the documents directory path, and that's not your fault, since it's exactly done this way, according to many knowledge bases.
As of the encoding, stringWithContentsOfFile is deprecated, please use stringWithContentsOfFile:encoding:error: (see the docs)
and you will be able to specify the correct encoding and get accurate error descriptions.
Related
I want to save audio file generated by TTS SDK.
I am not sure what is correct way to do it with NSURL path.
This is the code, but result says NO.
If I don't try saving audio file, MyAcaTTS works fine.
NSString *FileNamePath = [[NSBundle mainBundle] pathForResource:#"testAudio" ofType:#"aiff"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appSettingsPath = [documentsDirectory stringByAppendingPathComponent:FileNamePath];
NSURL *url=[[NSURL alloc]initWithString:appSettingsPath];
BOOL result = [MyAcaTTS_ startSpeakingString:#"testing" toURL:url];
Document of Acapela iPhone SDK.
6.2.3.startSpeakingString:toURL:
Synopsis
(BOOL)startSpeakingString:(NSString *)string toURL:url;
Description
Begins synthesizing string into a sound (AIFF) file.
When synthesis of string finishes normally or is stopped, the message
speechSynthesizer:didFinishSpeaking: is sent to the delegate. Parameters
string
Text to synthesize. When nil or empty, no synthesis occurs.
url
Filesystem location of the output sound file. Return value
YES when synthesis starts successfully, NO otherwise.
http://www.ecometrixem.com/cms-assets/documents/44729-919017.acapela-for-iphone.pdf
There are two things for you to consider in your code:
The line
NSString *FileNamePath = [[NSBundle mainBundle] pathForResource:#"testAudio" ofType:#"aiff"];
is not required since it returns full path of the file while you need only the last part of it: "testAudio.aiff"
You construct URL object with constructor accepting strings with valid protocol prefix, like "http://" or "ftp://" while your need another constructor named initFileURLWithPath: instead.
So with all the above your code may look like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appSettingsPath = [documentsDirectory stringByAppendingPathComponent:#"testAudio.aiff"];
NSURL *url=[[NSURL alloc]initFileURLWithPath:appSettingsPath];
BOOL result = [MyAcaTTS_ startSpeakingString:#"testing" toURL:url];
i am using following code to log into a file...
NSData *dataToWrite = [[NSString stringWithString:#"log data"] dataUsingEncoding:NSUTF8StringEncoding];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:#"fileName.txt"];
[dataToWrite writeToFile:path atomically:YES];
But when this method gets called again...it doest show the last entry...??
Could anyone suggest?
thanks
It is better you try using NSFileHandle , because the write operation to a file on NSData simply a convenience function and can not do a full fledged file operations like appending.
i can access .txt file from documents folder but how to access a folder content lets say documents/A
inside A i have ->a.html, update.cfg
now why i cant access update.cfg??
i am getting null value for zipPath
i tried this but no luck
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *aDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"A"];
NSString *zipPath = [[NSBundle mainBundle] pathForResource:#"update" ofType:#"cfg" inDirectory:aDirectory];
still zipPath=NULL??
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *aDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"A"];
My approach to get to the documentsfolder is a little bit different. (I hope you mean the Documents folder which every application has, not one created by yourself in the mainbundle.^^) I do it like this:
NSString *directoryPath = [[NSHomeDirectory() stringByAppendingPathComponent: #"Documents"] stringByAppendingPathComponent: #"A"];
This is the path to your directory called A in the documents folder. If you know the filename, than you can use another "stringByAppendingPathComponent". ;-) I hope it helps. Else ask again. :-D
after messing up i found this way to acces the file from folder
i got it
NSString *fileName = [NSString stringWithFormat:#"%#/update.cfg",
aDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
thanks
I am using the following code to open a file's contents and save it to another file.
when it runs the original file length is 793 but the saved file is 0. I have also tried just to copy the file. Nothing seems to work.
Is there some kind of permissions I'm missing on the documents directory?
NSError *error;
NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* nGram = [basePath stringByAppendingPathComponent:#"contacts.gram"];
NSString *oGram = [basePath stringByAppendingPathComponent:#"/../vText.app/model/lm/TAR9230/contacts.gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:oGram encoding:NSUTF8StringEncoding error:&error];
BOOL ok = [gramString writeToFile:nGram atomically:NO encoding:NSUnicodeStringEncoding error:&error];
if(!ok) NSLog(#"Mayday!");
NSLog(#"%d",[gramString length]);
gramString = [[NSString alloc] initWithContentsOfFile:nGram encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%d",[gramString length]);
This entire block is unnecessary. All you need is:
NSString *fp=[[NSBundle mainBundle] pathForResource:#"contacts" ofType:#"gram"];
NSString *gramString = [[NSString alloc] initWithContentsOfFile:fp
encoding:NSUTF8StringEncoding
error:&error];
You certainly don't want to try to directly access a file in the app bundle using a hardcoded path because the file isn't guaranteed to be in the same exact place in every build.
In the code you do have, you want to use the same encoding constant for reading as you did for writing. You write with NSUnicodeStringEncoding but you read with NSUTF8StringEncoding. These should overlap but why take the chance if you know the exact coding used?
I've one plist file and I want to parse it and copy it's content into NSArray,and code that I am using for that is.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *fooPath = [documentsPath stringByAppendingPathComponent:#"myfirstplist.plist"];
NSLog(fooPath);
self.myArray = [[NSArray arrayWithContentsOfFile:fooPath] retain];
NSLog(#"%#",myArray);
Now problem is very weird, sometime when I print myArray content it prints file data, and sometime it doesn't.
I am facing a same problem even when I use URL as my path.
self.myArray = [[NSArray arrayWithContentsOfURL:URlPath] retain];
what would be the reason?
Thanks in advance.
Depending on how you generated the .plist initially, you may run into problems if you try and read it back in as an array. The safest way to read a plist is using the NSPropertyListSerialization class: Apple Doc.
NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath = [bundle pathForResource: #"file-name" ofType:#"plist"];
NSArray *phrase2 = [NSArray arrayWithContentsOfFile: plistPath];
NSLog (#"%#", phrase2);
To get the path use
NSString *plistPath = [bundle pathForResource: #"file-name" ofType:#"plist"];
And then use it
NSArray *phrase2 = [NSArray arrayWithContentsOfFile: plistPath];
NSLog (#"%#", phrase2);
Are you generating the file with writeToFile:atomically: ? do you check that this returns true?
It was very stupid mistake,
I declared "myarray" properties as "retain and nonatomic" and during parsing operation I am retaining it again,
self.myArray = [[NSArray arrayWithContentsOfURL:URlPath] retain];
means I retained it but never released it.that's why that weird problem was there.
Cheers.