Try to write a string to file [duplicate] - ios

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];

Related

How to store a NSData locally

I am getting various format of documents with extension as .png,.txt,.jpg,,mp3 etc as NSData formatt, I need to store these locally and view it ,I have tried this
NSData* conData = [convStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"the converted string to nsdata is :%#",conData);
[conData writeToFile:#"Filename.txt" atomically:YES];
but unfortunately this is not working can any one help.
Note - writing NSData into a file is an IO operation which may block your main thread use dispatch, also provide file path for writing instead file name only.
This writes file for me
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Filename.txt"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
you should pass a correct path in writeToFile method
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *targetPatch = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"Filename.text"]];
[data writeToFile:targetPatch atomically:YES];
You have given only file name(Filename.txt) not whole file path thats why your code is not working.
Check below line of code you will get idea.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"Filename.txt"];
[urlData writeToFile:filePath atomically:YES];

How to create a .txt file programmatically on iOS

I am a new iOS developer. I want to create an app that will auto-create new *.txt files in the app's folder. I could only find how to open, close, save, write, and read - not create. How can I create new files? Thanks.
Use the following code to write/create a .txt file in your app's Documents directory. It should be pretty self-explanatory.
NSError *error;
NSString *stringToWrite = #"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:#"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
And to retrieve the text file:
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", str);
I hope this help's you
-(void)writeToTextFile{
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:#"%#/filename.txt",
documentsDirectory];
NSString *content = #"This is Demo";
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
-(void)ShowContentlist{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/filename.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
[content release];
}

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];

Read Text File in Document Folder - Iphone SDK

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.

Resources