IOS:复制文档文件夹中的文件

时间:2011-07-01 07:58:16

标签: ios xcode bundle

在我的项目中,我有两个文件.txt(在Resources文件夹中),如何将它们复制到文档文件夹中?

3 个答案:

答案 0 :(得分:114)

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

答案 1 :(得分:5)

Swift 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")
        }
    }
}

答案 2 :(得分:1)

while ((line = br.readLine()) != null)
{
 if(line.equals("1,2,3,4,5,6,7,8,char"))
   continue;
 //add if it's not that string
 viewList.add(line);
}