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];
Related
I'm getting a problem to find a file from project. I am getting this file using code but I can't get it using url.
Please help me out from this problem.
Here is the path of file
Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents/file.txt
Here is the code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *Path = [NSString stringWithFormat:#"%#/%#%#",documentsDirectory,#"file"#".txt"];
[str writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSString *fn=#"file";
NSString *searchFilename =[fn stringByAppendingString:#".txt"]; // name of the PDF you are searching for
NSArray *pathss = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorys = [pathss objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectorys];
NSString *documentsSubpath;
BOOL fileFound = false;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
fileFound=NO;
}
NSLog(#"found %#", documentsSubpath);
fileFound =YES;
}
if(fileFound){
NSLog(#"File Found");///this line is execute when i run this code
}
In code, you can use:
NSURL *fileURL = [NSURL URLWithPath: documentsSubpath];
And that will be the path to your file.
If you want to see the actual file, go to the Macintosh Finder and click "Go To Folder" (it's under the "Go" menu, or ⇧⌘G all together). Then type in your path MINUS the last path component, which is the filename. In your case, that is "/Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents".
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.
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];
}
I've spent the past few hours trying to figure this out, but I've ran out of ideas.
All I'm trying to do is archive an object, but the method archiveRootObject keeps on returning NO
Here's my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
cacheDirectory = [cacheDirectory stringByAppendingPathComponent:#"MyAppCache"];
NSString *fullPath = [cacheDirectory stringByAppendingPathComponent:#"archive.data"];
if(![[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSArray *array = [NSArray arrayWithObjects:#"hello", #"world", nil];
NSLog(#"Full Path: %#", fullPath);
BOOL res = [NSKeyedArchiver archiveRootObject:array toFile:fullPath];
if(res){
NSLog(#"YES");
}else{
NSLog(#"NO");
}
Every time time I run this, it prints NO.
Any help would be appreciated!
You create a directory with the path fullPath and then you try to write the file at the same path. Overwriting a directory with a file like this is not possible. Use your cacheDirectory string to create your directory.
NSString *cacheDirectory is not a mutable string and after you init it, you attempt to modify it so you are writing to the top-level directory.
For a quick fix, try:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([documentPaths count] > 0) ? [documentPaths objectAtIndex:0] : nil;
NSString *documentsResourcesPath = [documentPath stringByAppendingPathComponent:#"MyAppCache"];
NSString *fullPath = [documentsResourcesPath stringByAppendingPathComponent:#"archive.data"];
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.