目錄:
1、txt文件寫入
2设联、txt文件讀取
3善已、rtf文件讀取
4、NSString轉(zhuǎn)換成其他類型數(shù)據(jù)方法
1离例、txt文件寫入
//獲取文件路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *newPath= [documentsDirectory stringByAppendingPathComponent:@"newFile.txt"];
//要寫入txt文件的內(nèi)容
NSString *fileContent = @"Write to file...";
//寫入文件方法1.使用文件管理的方式寫入內(nèi)容
NSFileManager *fileManager = [[NSFileManager alloc]init];
NSData *fileData = [fileContent dataUsingEncoding:NSUTF8StringEncoding];
[fileManager createFileAtPath:newPath contents:fileData attributes:nil];
//寫入文件方法2.直接寫入字符串內(nèi)容
[arr writeToFile:pathStr atomically:YES];
NSError *error = nil;//數(shù)組寫入方法
[fileContent writeToFile:newPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!error)
{
NSLog(@"字符串寫入成功换团!");
}
else
{
NSLog(@"字符串寫入失敗,原因是:%@",[error localizedDescription]);
}
2宫蛆、txt文件讀取
//讀取txt文件內(nèi)容
NSString *str = [NSString stringWithContentsOfFile:newPath encoding:NSUTF8StringEncoding error:&error];
if (!error)
{
NSLog(@"txt內(nèi)容為:%@",str);
}
else
{
NSLog(@"文件讀取失敗艘包,原因是:%@",[error localizedDescription]);
}
3、rtf文件讀取
rtf文件不能像txt文件一樣直接讀取文件內(nèi)容,
在此我的方法是把rtf內(nèi)容轉(zhuǎn)換成txt之后再讀认牖ⅰ:
轉(zhuǎn)換方式1卦尊、如有虛擬機(jī)裝有Windows系統(tǒng)則直接創(chuàng)建txt文件,復(fù)制內(nèi)容即可舌厨。但是此時需要注意岂却,讀取此txt文件時會報錯:The file “NewData.txt” couldn’t be opened using text encoding Unicode (UTF-8).需要特殊處理如下:
if (error) //解析錯誤時打印錯誤信息
{
//error == The file “NewData.txt” couldn’t be opened using text encoding Unicode (UTF-8).
NSLog(@"error == %@",[error localizedDescription]);
if (!str) //解析錯誤時按GBK編碼再解碼一次
{
str = [NSString stringWithContentsOfFile:newPath encoding:0x80000632 error:nil];
}
}
轉(zhuǎn)換方式2、沒有Windows虛擬機(jī)時裙椭,需要自己用代碼創(chuàng)建一個txt文件(其他方式不會)淌友,方法如前所述,創(chuàng)建txt文檔后復(fù)制rtf文件內(nèi)容即可骇陈,此時不用做特殊處理即可讀取文件內(nèi)容震庭。
至于直接改文件名字的方式會出現(xiàn)亂碼的情況
4、NSString轉(zhuǎn)換成其他類型數(shù)據(jù)方法
在獲取到文件內(nèi)容的字符串之后你雌,有時需要把字符串格式轉(zhuǎn)換成想要的格式器联,可以通過NSData過渡一下,進(jìn)行轉(zhuǎn)換婿崭。
//NSString轉(zhuǎn)換其他數(shù)據(jù)類型 //首先轉(zhuǎn)換成NSData類型
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//NSData類型轉(zhuǎn)換成字典 //數(shù)組拨拓、字典、字符串等接收即可
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];