2014-03-13 89 views

回答

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

輸出爲空。 – biki

+0

'firstFileContent'的輸出是什麼? –

+0

我的文本文件在文檔目錄中,所以而不是從那裏訪​​問..我正在使用[[NSBundle mainBundle] pathForResource:ofType:];爲了訪問它,我,我得到了錯誤,因爲filecontents輸出爲NULL。但現在我得到它是正確的。感謝您的時間。 – biki

1
以下代碼 NSString文件和使用

首先加載內容:

NSString *strConcatenate = [NSString stringWithFormat:@"%@ %@ %@", textfiles1, textfiles2, textfiles3];  
    NSLog(@"%@", strConcatenate); 
0

你只需要在文件的內容加載到NSMutableString和將它們連接起來:

NSMutableString *myString = @"Content of the first file"; 
NSString *test = [myString stringByAppendingString:@" content of the second file"]; 
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); 
} 
相關問題