2011-05-06 115 views

回答

2

這當然是可能的;它只是取決於文本文件的確切格式。
讀取文本文件的內容很簡單:

// If you want to handle an error, don't pass NULL to the following code, but rather an NSError pointer. 
NSString *contents = [NSString stringWithContentsOfFile:@"/path/to/file" encoding:NSUTF8StringEncoding error:NULL]; 

這將創建一個包含整個文件的自動釋放的字符串。如果所有的文件中包含是一個整數,你可以這樣寫:

NSInteger integer = [contents integerValue]; 

如果文件被分成多行(包含一個整數每行),你必須把它分裂:

NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 
for (NSString *line in lines) { 
    NSInteger currentInteger = [line integerValue]; 
    // Do something with the integer. 
} 

總的來說,這很簡單。


回寫到文件也一樣容易。一旦你操縱了你想要的字符串,你可以使用這個:

NSString *newContents = ...; // New string. 
[newContents writeToFile:@"/path/to/file" atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 

你可以使用它來寫入字符串。當然,你可以玩這些設置。將atomically設置爲YES會導致它首先寫入測試文件,驗證它,然後將其複製以替換舊文件(這可確保如果發生某些故障,最終不會收到損壞的文件)。如果你願意,你可以使用不同的編碼方式(儘管NSUTF8StringEncoding是強烈推薦的),如果你想要發現錯誤(你本質上應該這樣做),你可以在方法中傳入一個NSError的引用。這將是這個樣子:

NSError *error = nil; 
[newContents writeToFile:@"someFile.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error]; 
if (error) { 
    // Some error has occurred. Handle it. 
} 

如要進一步瞭解,請諮詢NSString Class Reference

+0

你會如何寫多行? Apple文檔提到'writeToFile'將在每次調用時刪除舊文件,因此只是循環執行多個'writeToFile'調用不起作用。有沒有辦法用'newLineCharacterSet'來寫? – GeneralMike 2013-04-11 20:09:18

+0

明白了 - 你完全不用'newLineCharacterSet'來寫,但是你可以使用'\ r \ n'指定一個換行符。查看我的答案瞭解更多詳情。 – GeneralMike 2013-04-11 20:44:14

0

如果您必須寫入多行,請在生成newContents字符串時使用\r\n來指定要放置換行符的位置。

NSMutableString *newContents = [[NSMutableString alloc] init]; 

for (/* loop conditions here */) 
{ 
    NSString *lineString = //...do stuff to put important info for this line... 
    [newContents appendString:lineString]; 
    [newContents appendString:@"\r\n"]; 
}