IOS: скопировать файл в папку документов - PullRequest
40 голосов
/ 01 июля 2011

В моем проекте у меня есть два файла .txt (в папке «Ресурсы»), как их скопировать в папку с документами?

Ответы [ 3 ]

115 голосов
/ 01 июля 2011

Копирует txtFile из ресурса в документ, если его еще нет.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"txtFile.txt"];

if ([fileManager fileExistsAtPath:txtPath] == NO) {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
    [fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
}

Если вы хотите перезаписывать каждый раз, попробуйте следующее:

if ([fileManager fileExistsAtPath:txtPath] == YES) {
    [fileManager removeItemAtPath:txtPath error:&error];
}

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
5 голосов
/ 11 января 2017

Свифт 3

код для файла существует или нет, если нет, то скопируйте.

func CheckFileisExistOrNot(strPath:String) {
    let filemgr = FileManager.default
    if !filemgr.fileExists(atPath: strPath) {
        let resorcePath = Bundle.main.path(forResource: "\(Global.g_databaseName)", ofType: ".db")
        do {
            try filemgr.copyItem(atPath: resorcePath!, toPath: strPath)
        }catch{
            print("Error for file write")
        }
    }
}
1 голос
/ 17 декабря 2015
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0]stringByAppendingString:@"csvfile"];

NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"sample.csv"];

if ([fileManager fileExistsAtPath:txtPath] == NO) {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@".csv"];
    [fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
...