How to copy all text file from document directory in iOS? - ios

I need to Copy all text files (.txt) from document directory into my folder name "Text".
I can copy only one files.
I want to copy like (*.txt) with one touch.
Here codes is my single file copy.
self.fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *cutExtension = [tblGetNameToMove.textLabel.text stringByDeletingPathExtension];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.txt",cutExtension]];
NSString *fileName = [NSString stringWithFormat:#"%#/Text/%#.txt",documentsDirectory,cutExtension];
[self.fileManager copyItemAtPath:txtPath toPath:fileName error:&error];
How can i do that?

Get all the contents in the folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] directoryContentsAtPath:documentsDirectory];
Enumerate over the files list and check if it constains .txt
[fileList enumerateObjectsUsingBlock:^(NSString *string, NSUInteger index, BOOL *stop) {
if ([string hasSuffix:#".txt"]) {
[[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error];
}
}];
Update
Updated my answer according to comments by Martin R
Update 2
As pointed out by Hot Licks use
if ([[string pathExtension] isEqualToString:#"txt"]) {
To check for the file extension.

Related

How to find a file in Project?

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".

saving and retrieving files to an array in documents directory Xcode iOS

I have an app that I want to save a username for each person that I play a game with and then retrieve it into an array that can be used to create headers for a tableview. I am using this code to save the files.
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *slash2 = [documentsDirectory stringByAppendingString:#"/Names"];
if (![[NSFileManager defaultManager] fileExistsAtPath:slash2])
[[NSFileManager defaultManager] createDirectoryAtPath:slash2 withIntermediateDirectories:NO attributes:nil error:&error1];
//yourName is the userName of the challenger
NSString *fullPath = [slash2 stringByAppendingPathComponent:yourName];
and when I look at the path
NSLog(#"path :%#",fullPath);
I get
"Names/Mary",
"Names/John",
I would like to then get these names form the documents directory into an array to use is the tableview. I have tried
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *slasha = [documentsDirectory stringByAppendingPathComponent:#"/Names"];
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:slasha];
for (NSString *element in arrayFromFile)
NSLog(#"Names: %#", element);
but nothing shows up
What am I doing wrong and how can I do this
user1114881,
Creating folders to show challengers name in tableView header, Seriously ??? I will say its a very wrong approach.
That being said, now let me fix your problem,
NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *slash2 = [documentsDirectory stringByAppendingString:#"/Names"];
if (![[NSFileManager defaultManager] fileExistsAtPath:slash2])
[[NSFileManager defaultManager] createDirectoryAtPath:slash2 withIntermediateDirectories:NO attributes:nil error:&error1];
//yourName is the userName of the challenger
NSString *fullPath = [slash2 stringByAppendingPathComponent:yourName];
BOOL Success = [[NSFileManager defaultManager] createFileAtPath:fullPath contents:nil attributes:nil];
Mistake you were doing was, you never created a file for the user, you just created a folder called Names. You need to call createFileAtPath to create file.
In order to read all the files in folder use
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *slasha = [documentsDirectory stringByAppendingPathComponent:#"/Names"];
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:slasha error:nil];
You must be able to see the list of all files inside folder Names now :)
Happy coding.

Get contents of a specific folder in documents diectory

Im trying to read contents of a specific folder in documents directory thats contains only png's /Documents/ApplianceImagesFolder/
Currently I can only get all my images from documents folder, how can I target contents of ApplianceImagesFolder only?
//gets all png form documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *dir in dirContents) {
if ([dir hasSuffix:#".png"]) {
NSRange range = [dir rangeOfString:#"."];
NSString *name = [dir substringToIndex:range.location];
if (![name isEqualToString:#""]) {
[fileList addObject:name];
}
}
}
NSLog(#"document folder content list %# ",fileList);
Build the desired path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:#"ApplianceImagesFolder"];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];
And there's a better way to find the png files:
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);

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

How to Read a file from documents directory in iOS

I need to search a file in documents directory of iOS but i don't know the extension of that file. How to search the file without extension.
Below is the code if you know the filename.extension(abc.txt). How can i search for the same file with jsut filename(abc)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"abc.txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:NULL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *fileWithExt = nil;
for (NSString *file in directoryContent )
{
if([file stringByDeletingPathExtension] isEqualsTo:#"abc"]
{
fileWithExt = file;
break;
}
}
P.S. : The fileWithExt will contain the first file with name abc

Resources