對NSFileHandle 的用法一直不熟練客冈, 無意間找到的詳細(xì)介紹姜胖,留底方便使用
NSFileHandle ?此類主要是對文件內(nèi)容進(jìn)行讀取和寫入操作
NSFileMange ? 此類主要是對文件進(jìn)行的操作以及文件信息的獲取
常用處理方法
+?(id)fileHandleForReadingAtPath:(NSString *)path??打開一個(gè)文件準(zhǔn)備讀取
+?(id)fileHandleForWritingAtPath:(NSString?*)path??打開一個(gè)文件準(zhǔn)備寫入
+?(id)fileHandleForUpdatingAtPath:(NSString?*)path??打開一個(gè)文件準(zhǔn)備更新
-??(NSData?*)availableData;?從設(shè)備或通道返回可用的數(shù)據(jù)
-??(NSData?*)readDataToEndOfFile;?從當(dāng)前的節(jié)點(diǎn)讀取到文件的末尾
-??(NSData?*)readDataOfLength:(NSUInteger)length;?從當(dāng)前節(jié)點(diǎn)開始讀取指定的長度數(shù)據(jù)
-??(void)writeData:(NSData?*)data;?寫入數(shù)據(jù)
-??(unsigned long long)offsetInFile;??獲取當(dāng)前文件的偏移量
-??(void)seekToFileOffset:(unsigned long long)offset;?跳到指定文件的偏移量
-??(unsigned long long)seekToEndOfFile;?跳到文件末尾
-??(void)truncateFileAtOffset:(unsigned long long)offset;?將文件的長度設(shè)為offset字節(jié)
-??(void)closeFile;??關(guān)閉文件
向文件追加數(shù)據(jù)
NSString *homePath??= NSHomeDirectory(?);
NSString *sourcePath?=?[homePath stringByAppendingPathConmpone:@"testfile.text"];
NSFileHandle *fielHandle?=?[NSFileHandle fileHandleForUpdatingAtPath:sourcePath];
[fileHandle seekToEndOfFile];??將節(jié)點(diǎn)跳到文件的末尾
NSString *str?=?@"追加的數(shù)據(jù)"
NSData* stringData ?=?[str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:stringData];?追加寫入數(shù)據(jù)
[fileHandle closeFile];
定位數(shù)據(jù)
NSFileManager *fm?=?[NSFileManager defaultManager];
NSString *content?=?@"abcdef";
[fm createFileAtPath:path contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSFileHandle *fileHandle?=?[NSFileHandle fileHandleForReadingAtPath:path];
NSUInteger length =?[fileHandle availabelData] length];?獲取數(shù)據(jù)長度
[fileHandle seekToFileOffset;length/2];?偏移量文件的一半
NSData *data?=?[fileHandle readDataToEndOfFile];
[fileHandle closeFile];
復(fù)制文件
NSFileHandle *infile,?*outfile;?輸入文件艾少、輸出文件
NSData?*buffer;?讀取的緩沖數(shù)據(jù)
NSFileManager?*fileManager?=?[NSFileManager defaultManager];
NSString *homePath?= NSHomeDirectory(?);
NSString *sourcePath?=?[homePath stringByAppendingPathComponent:@"testfile.txt"];??源文件路徑
NSString *outPath?=?[homePath stringByAppendingPathComponent:@"outfile.txt"];?輸出文件路徑
BOOL sucess ?=?[fileManager createFileAtPath:outPath contents:nil attributes:nil];
if (!success)
{
return N0;
}
infile =?[NSFileHandle fileHandleForReadingAtPath:sourcePath];?創(chuàng)建讀取源路徑文件
if (infile?== nil)
{
return NO;
}
outfile =?[NSFileHandle fileHandleForReadingAtPath:outPath];?創(chuàng)建病打開要輸出的文件
if (outfile?== nil)
{
return NO;
}
[outfile truncateFileAtOffset:0];?將輸出文件的長度設(shè)為0
buffer?=?[infile readDataToEndOfFile];??讀取數(shù)據(jù)
[outfile writeData:buffer];??寫入輸入
[infile closeFile];????????關(guān)閉寫入啤覆、輸入文件
[outfile closeFile]帐要;