Read Text File in Document Folder - Iphone SDK - ios

I have this code below:
NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:#"recentDownload"];
NSString *fullPath = [NSBundle pathForResource:fileName ofType:#"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:#"/Documents/"]];
NSError *error = nil;
[textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]];
textviewerdownload is the textview displaying the text from the file. The actual file name is stored in an NSUserDefault called recentDownload.
When I build this, I click the button which this is under, and my application crashes.
Is there anything wrong with the syntax or just simple error?

The NSBundle class is used for finding things within your applications bundle, but the Documents directory is outside the bundle, so the way you're generating the path won't work. Try this instead:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:#"recentDownload.txt"];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:#"myfile.txt"];
if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"txt"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
}
//Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];
This worked for me
Anyway, thank you all..

For read/write from text file check this url.

Related

How do I write a string to a file?

I have a .txt file with a small password in it. I would like to change that file's text. How can I do that? I can get the file's text using :
NSString *passWord = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"password" ofType:#"txt"] encoding:NSUTF8StringEncoding error:NULL];
But I can't seem to find a way to replace the contents of the file with a string.
The way to do this is to remove old file and create new one.
Removing existing file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"myFile.txt"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:filePath])
{
[fileManager removeItemAtPath:filePath error:&error];
}
To crate new file with your new password write password data while creating file as:
[createFileAtPath:path contents:[NSData data] attributes:nil]

writeToFile working on iOS 7 not on iOS 6

I have been having an issue and I can't find anything about it.
I got some code to write files in the Documents folder with iOS. Checked the Apple documentation seems it's where I want to put the file for it to be available the next launch.
Here's the code I'm using:
- (void) writeToTextFile:(NSString *)logMessage inFile:(NSString *)fileName
{
//get the documents directory:
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 *filePath = [NSString stringWithFormat:#"%#/%#.txt", documentsDirectory, fileName];
NSLog(#"TEST path: %#", filePath);
//save logMessage to the documents directory
[logMessage writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];
}
Now I'm using unit tests on this methods. It was working fine on the iOS 7.0.3 simulator, but when I switched to iOS 6.0 it doesn't work anymore.
In fact I found out that there was no Documents folder in "Application Support/iPhone Simulator/6.0/" but there's one in the 7.0.3 folder.
I can't really find any differences on how writing to a file should be handled between 6 and 7. Should I test if the folder exists then create it if it's not there?
This works for me
NSString *string = #"Text to save";
NSString *filePath = #"filerecord.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:filePath];
[string writeToFile:filePath atomically:YES];
UPDATE
Create Documents directory if not exists
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (![fileManager fileExistsAtPath:documentsDirectory]) {
[fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *string = #"Text to save";
NSString *filePath = #"filerecord.txt";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filePath];
[string writeToFile:filePath atomically:YES];

How to copy text file from document directory in iOS

Hello i am trying to copy text file from document directory into folder name Temp that located in document directory.
Here is some of code i tried and didn't work.
self.fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentsDirectoryToTemp = [NSString stringWithFormat:#"%#/Temp/",[paths objectAtIndex:0]];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt",tblGetNameToMove.textLabel.text]];
[self.fileManager copyItemAtPath:txtPath toPath:documentsDirectoryToTemp error:&error];
How can i do that?
There could be many reasons for this :
First try to print all the path like documentsDirectoryToTempn and txtPath whether it is correct or not .
The second thing is make use that error variable :
if(error)
{
NSLog("Error while coping :%#",[error localizedDiscription]);
}
so you can track exact problem .
Here is solution. I need to add directory and also name of file and extension.
Here is codes.
self.fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt",tblGetNameToMove.textLabel.text]];
NSString *fileName = [NSString stringWithFormat:#"%#/Temp/%#.txt",documentsDirectory,tblGetNameToMove.textLabel.text];
[self.fileManager copyItemAtPath:txtPath toPath:fileName error:&error];

Try to write a string to file [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Problem in writing to a file in application bundle
I am trying to write a String to a file using the following code :
NSString *file = [[NSBundle mainBundle] pathForResource:#"settings" ofType:#"txt"];
NSLog(#"Path : , %#", file);
NSError *error=NULL;
NSString *data=#"teleiwne";
[data writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:&error];
The print out of Path is : /Users/kd/Library/Application Support/iPhone Simulator/6.0/Applications/763B8245-CB1A-4BDE-85CF-19AEFA411DB8/testKremala.app/settings.txt
I don't get any error but nothing is written to file
I tried the following code and it worked :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"set.txt"];
NSString *data=#"Kostas";
[data writeToFile:appFile atomically:YES];
NSString *myData = [NSString stringWithContentsOfFile:appFile];
NSLog(#"Data : %# ",myData);
You aren't allowed to write to the App directory. Try writing to the Documents directory inside that app folder.
NSString *data = #"testData";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"settings.txt"];
[data writeToFile:appFile atomically:YES];

unable to save plist ios

I m able to save the plist file in Simulator but I m not able to save the Plist file in the device. Any suggestion.
I m using
NSString* dictPath = [[NSBundle mainBundle] pathForResource:#"Dictionary" ofType:#"plist"];
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];
to read the files
and
[dict writeToFile:dictPath atomically: YES];
to write to file.
You can not write in to main bundle. You only can read from main bundle. If you want to write an file you need to place it in to the documents directory of your app.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
If you need the plist from the main bundle you can copy it first in to the documents directory then modify it. It is advised to have a check to ensure it is copied only once.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){
NSLog(#"File don't exists at path %#", path);
NSString *plistPathBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:#"plist"];
[fileManager copyItemAtPath:plistPathBundle toPath: path error:&error];
}else{
NSLog(#"File exists at path:%#", path);
}
Generally you would store these in ~/Documents or in ~/Library depending on the file. The question What is the documents directory (NSDocumentDirectory)? includes the documentation links and sample code you need to understand this.
You need to save the plist in Documents directory
to write
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:#"Dictionary"];
NSDictionary * dict = ...; //Construct your dictionary
[dict writeToFile:dictPath atomically: YES];
to read
NSDictionary * dict = [[NSDictionary alloc] initWithContentsOfFile:dictPath];

Resources