Nsfilehandle
Nsfilemanager class mainly for file operation (delete, modify, move, assign value, etc.)
// to determine if there is a tagetpath file path, create no
nsfilemanager *filemanage = [nsfilemanager defaultmanager];
BOOL success = [Filemanage createfileatpath: Tagetpath contents:nil attributes :nil];
if (success) {
NSLog(@ "Create success");
}
The Nsfilehandle class primarily reads and writes the contents of a file
Nsfilehandle steps to process a file
1: Create a Nsfilehandle object
// Create flow
nsfilehandle *infilehandle = [nsfilehandle filehandleforreadingatpath: Srcpath];
nsfilehandle *outfilehandle = [nsfilehandle filehandleforwritingatpath: Tagetpath];
2: I/O operations on open files
//Get file path
nsstring *homepath = nshomedirectory();
nsstring *filepath = [HomePath stringbyappendingpathcomponent:@ "Phone/date.text"];
Nsfilehandle *filehandle = [nsfilehandle filehandleforupdatingatpath: FilePath];
Navigate to the last
[filehandle seektoendoffile];
//Navigate to a location, after 100 bytes
[FileHandle seektofileoffset:];
// Append Data
nsstring *str = @ "Add World";
nsdata *stringdata = [str datausingencoding:nsutf8stringencoding];
// Append write Data
[FileHandle writedata: stringdata];
3: Close File object operation
Close the stream
[FileHandle closefile];
Common processing methods, reading
Read File contents
void Readbyfile () {
// file path
nsstring *homepath = nshomedirectory();
nsstring *filepath = [HomePath stringbyappendingpathcomponent:@ "Phone/cellphone.text" ];
nsfilehandle *filehandle = [nsfilehandle filehandleforreadingatpath: FilePath];
nsinteger length = [filehandle availabledata]. Length;
// jump to the specified location
[FileHandle seektofileoffset: length/2];
nsdata *data = [FileHandle readdatatoendoffile];
nsstring *str = [[nsstring alloc] initwithdata:d ata encoding: Nsutf8stringencoding];
NSLog(@ "%@", str);
[FileHandle closefile];
}
Copying Files
void Copy2other () {
nsstring *homepath = nshomedirectory();
nsstring *filepath = [HomePath stringbyappendingpathcomponent:@ "Phone/cellphone.text"];
nsstring *tagetpath = [HomePath stringbyappendingpathcomponent:@ "Phone/cellphone_bak.text" ];
// Do you have this file, no then create
nsfilemanager *filemanage =[nsfilemanager defaultmanager];
BOOL success = [Filemanage createfileatpath: Tagetpath contents:nil attributes :nil];
if (success) {
NSLog(@ "Create success");
}
// Read the source file via Nsfilehandle , write to another file
nsfilehandle *outfilehandle = [nsfilehandle filehandleforwritingatpath: Tagetpath];
nsfilehandle *infilehandle = [nsfilehandle filehandleforreadingatpath: FilePath];
nsdata *data = [Infilehandle readdatatoendoffile];
[Outfilehandle writedata:d ATA];
// close stream
[Infilehandle closefile];
[Outfilehandle closefile];
}
Introduction to File read classes (Nsfilehandle) in OC and common usage methods