我遇到了大麻烦。我想将多个文本文件的数据连接到另一个文本文件中。但是我不能。你能帮助我吗 ?非常感谢
答案 0 :(得分:2)
逐个阅读每个文件,
NSString *firstFileContent = [NSString stringWithContentsOfFile:<your file path>
encoding:NSASCIIStringEncoding
error:nil];
//Similarly read other files, and store them in secondFileContent and thirdFileContent.
//now concatenate all to form one big string.
NSString *bigString = [NSString stringWithFormat:@"-First File- \n%@ \n-Second File- \n%@\n-Third File-\n%@",firstFileContent, secondFileContent, thirdFileContent];
//write to file, create a new one
[bigString writeToFile:<path to write>
atomically:YES
encoding:NSASCIIStringEncoding
error:nil];
修改1 :
根据您的评论,您的文件位于DocumentDirectory中,请使用以下代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:<your file name>];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
答案 1 :(得分:1)
首先在NSString
中加载文件内容并使用以下代码:
NSString *strConcatenate = [NSString stringWithFormat:@"%@ %@ %@", textfiles1, textfiles2, textfiles3];
NSLog(@"%@", strConcatenate);
答案 2 :(得分:0)
您只需将文件内容加载到NSMutableString
并连接它们:
NSMutableString *myString = @"Content of the first file";
NSString *test = [myString stringByAppendingString:@" content of the second file"];
答案 3 :(得分:0)
你需要从包中读取文本文件然后附加它们,一旦你有,然后将其写回。我写了这个例子,希望你能从中学习。
NSMutableString *mutableString = [[NSMutableString alloc] init];
NSArray *textFiles = @[ @"textfile1", @"textfile2", @"textfile3" ];
for (NSString *textFileName in textFiles) {
NSString *path = [[NSBundle mainBundle] pathForResource:textFileName
ofType:@"txt"];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (content) {
[mutableString appendFormat:@"%@\n", content];
} else {
NSLog(@"%@", error.localizedDescription);
}
}
NSLog(@"%@", mutableString);
NSError *error = nil;
BOOL result = [mutableString writeToFile:@"concatenated_file.txt" atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!result) {
NSLog(@"%@", error.localizedDescription);
}