1, for the Nsfilemanager class, the path name of the file can be identified only by a file name or directory. Each pathname is a NSString object. This path can be a relative path or an absolute path.
2. The absolute path starts with a slash (/) and the slash is the root directory. A special generation character (~) identifies the user's home directory. However, you should try to avoid using hard-coded pathname in your program, and you should use methods and functions to work with paths or files.
3, all the operation of the file through the operation of the Nsfilemanager class, the object of the Nsfilemanager class can be understood as a file processing agent , all operations must be done through this agent.
4, the Nsfilemanager class is created as follows:
Nsfilemanager FM;
FM = [Nsfilemanager defaultmanager];
You can then manipulate the file by manipulating the FM object, such as deleting a file named "ToDoList" in the current directory, using the following code:
if ([FM removeItemAtPath: @ "ToDoList" error:null] = = NO) {
NSLog (@ "couldn ' t remove");
return 1;
}
It can be noted that the method has a return value and is a bool value.
5. The following code shows the main file operation Methods of the Nsfilemanager class:
(1) 、...
NSString *fname = @ "Testfile";
Nsfilemanager *FM;
FM = [Nsfilemanager defaultmanager];
if ([FM Fileexistsatpath: fName] = = NO) {
NSLog (@ "not exsit");
[FM Creatfileatpath:fName contents:nil attributes:nil];
return 1;
}
...
Note Fileexistsatpath: The method also has a return value, is a value of type bool;
(2) 、...
if ([FM copyitematpath:fName topath:@ "NewFile" error:NULL] = = NO) {
NSLog (@ "Copy file failed");
return 2;
}
...
copy files;
(3) 、...
if ([FM contentsequalatpath:fName Andpath:@ "NewFile"] = = NO) {
NSLog (@ "Files is not equal");
return 3;
}
...
Compares two files for the same;
(4) 、...
if ([FM Moveitematpath:@ "NewFile" Topath:@ "Newfile2" error:NULL] = = NO) {
NSLog (@ "File rename failed");
return 4;
}
...
renaming files;
(5) 、...
Nsdictionary *attr;
if (attr = [FM attributesofitematpath:@ "Newfile2" error:NULL]) = = nil) {
NSLog (@ "couldn ' t get file attributes");
return 5;
}
NSLog (@ "File size is%llu", [[attr Objectforkey: nsfilesize] unsignedlonglongvalue]);
...
Gets the size of the file, Attributesofitematpath: The return value is a Nsdictionary class object, and the last to use the key "Nsfilesize" to read out the size of the file;
(6) 、...
if ([FM removeitematpath:fName Error:NULL] = = NO) {
NSLog (@ "file removal failed");
return 6;
}
...
Delete the file, also note removeitematpath: The return value of the function is the bool type;
(7) 、...
NSLog (@ "%@", [nsstring stringwithcontentsoffile:@ "Newfile2" Encoding: Nsutf8stringencoding Error:NULL]);
...
Displays the contents of the Newfile2 file;
(8), use method copyItemAtPath:toPath:error: Copy file or method MoveItemAtPath:toPath:error: When moving the file, if only specify the target directory, is unable to copy or move the file into this directory, You need to explicitly specify the file name in the target directory;
(9), method MoveItemAtPath:toPath:error: Not only for moving files, you can also move the directory. If two paths refer to a file in the same directory, the effect is simply to rename the file;
(10), StringWithContentsOfFile:encoding:error: Method, the encoding parameter is used to specify how the characters in the file are to be displayed, Use nsutf8stringencoding to indicate that the file contains regular UTF8 ASCII characters;
(11), in this test program, in every possible error place return a different number, so that when debugging can be measured by the return value where the error occurred.
6, about NSData class:
(1), NSData class object is a buffer of the contents of a file, read the contents of the file into the buffer, or write the contents of the buffer to the file. Theoretically NSData objects can store 2GB to 8EB of data;
(2), understand the following code:
...
NSData *filedata;
FILEDATA = [FM contentsatpath:@ "Newfile2"]; Read content from Newfile2
if ([FM Createfileatpath:@ "Newfile3" contents:fileData attributes:NULL] = = NO) {
NSLog ("couldn ' t create file"); Write the content into the newfile3.
return 1;
}//write the content to the new file in the IF statement, which is useful or Createfileatpath: method
7. The following code shows the main directory operation Methods of the Nsfilemanager class:
(1) 、...
PATH = [FM currentdirectorypath];
NSLog (@ "The current path is%@", path);
...
Gets the current directory;
(2) 、...
NSString *dirname = @ "TestDir";
if ([FM createdirectoryatpath:dirName withintermediadirectories:YES attributes:nil Error:NULL] = = NO) {
NSLog (@ "couldn ' t create directory");
return 1;
}
...
Create a new directory under the current directory;
(3) 、...
if ([FM moveitemtopath:dirName topath:@ "Newdir" error:NULL] = = NO) {
NSLog (@ "directory rename failed");
return 2;
}
...
Rename the folder, this method is actually renaming the file method;
(4) 、...
if ([FM Changecurrentdirectorypath:@ "Newdir"] = = NO) {
NSLog (@ "Change directory failed");
return 3;
}
...
Change the current directory to a new directory;
8, about the contents of the enumeration directory, there are two ways to see the following code:
...
NSString *path; Current path, definition procedure ignored
Nsfilemanager *FM; Define procedure Ignore
nsdirectoryenumerator *direnum;
Nsarray *dirarray;
...
The first enumeration method, using the Nsenumerator class
DIRENUM = [FM enumeratoratpath: path];
NSLog (@ "Contents of%@", path);
while (path = [Direnum nextobject])! = nil) {//nextobject is a nsenumerator only method
NSLog (@ "%@", Path);
}
...
The second method of enumeration
Dirarray = [FM contentsofdirectoryatpath: [FM Currentdirectorypath] error:NULL];
for (path in Dirarray) {
NSLog (@ "%@", Path);
}
...
About these two methods:
(1), using Enumeratoratpath: The method can not only enumerate the files in the directory, even the directory contains directories, but also recursively enumerate the contents of subdirectories, and even subdirectories of the contents of the subdirectory, it will exhaust all the files in this folder. The use of Contentsofdirectoryatpath: The method is merely to enumerate the contents of the next level of the catalogue;
(2), two methods will enumerate all types of files, even including folders;
(3), use the following method to block the Enumeratoratpath: Method recursively enumerates the contents of a subfolder:
...
while (path = [Direnum nextobject]) = nil) {
NSLog (@ "%@", Path);
[FM Fileexsitsatpath: path isdirectory:&flag]
Use this method to determine whether the content read in the Direnum is not a folder,
If it is a folder, flag will be set to Yes;
if (flag = = YES) {
[Direnum skipdescendents]; This method can prevent Direnum from enumerating subfolders
}
}
...
9, about the use of the path of some methods:
(1), the operation of the pathname is mainly using the method provided by NSPathUtilities.h , NSPathUtilities.h is included in the Foundation.h. The following code shows:
(2) 、...
NSString *tempdir;
TempDir = nstemporarydirectory ();
NSLog (@ "Temporary directory is%@", tempdir);
...
Gets the current temp directory;
(3) 、...
NSString *path;
Nsfilemanager *FM;
FM = [Nsfilemanager Defaultmanager];
PATH = [FM Currentdirectorypath];
NSLog (@ "Base dir is%@", [path lastpathcomponent]);
...
Gets the base file name or folder name, which is the name of the last component of the path;
(4) 、...
NSString *fname = @ "PATH.M";
NSString *fullpath;
FullPath = [path stringbyappendingpathcomponent: fName];
NSLog (@ "FullName to%@ is%@", FName, FullPath);
...
Get the full path, including the file name;
(5) 、...
NSString *extension;
Extension = [FullPath pathextension];
NSLog (@ "extension for%@ is%@", fullpath, extension);
...
Gets the extension of the file and returns an empty string if no extension is in place;
(6) 、...
NSString *homedir;
Homedir = nshomedirectory ();
NSLog (@ "Your home directory is%@", homedir);
...
Get the user's home directory, and if you use Nshomedirectoryforuser () You can also get the other user's home directory;
(7) 、...
Nsarray *component;
component = [Homedir pathcomponent];
For (path in component) {
NSLog (@ "%@", Path);
}
...
Each component of the home directory is opened in an array;
10, about using the Nsfilehandle class on the operation of the file:
(1) 、...
Nsfilehandle*infile;
InFile = [Nsfilehandle filehandleforreadingatpath:@ "Testfile"];
...
Set the Testfile file as the Read object;
(2) 、...
Nsfilehandle *outfile;
OutFile = [Nsfilehandle filehandleforwritingatpath:@ "Testout"];
...
Set the Testout file as the Write object;
(3) 、...
[OutFile Truncatefileatoffset:0];
...
Intercept the file to only a few bytes left;
(4) 、...
NSData *buffer;
Buffer = [InFile readdatatoendoffile];
[OutFile WriteData: buffer];
...
Write the contents of infile to outfile;
(5) 、...
[InFileCloseFile];
[OutFile CloseFile];
...
Remember to close the file;
(6) 、...
NSLog (@ "%@", [NSString stringwithcontentsoffile:@ "testout" encoding: nsutf8stringencoding Error:NULL]);
...
Read the contents of the Testout file;
11. The offset of the location of the anchor point in the file:
Suppose you have defined the file Filea and file Fileb, define the operation to read the file Filehandlea and write the operation of the file Filehandleb, if you want to append Filea content to Fileb, then set the Fileb anchor point to the end of the file, Use the following methods:
[Filehandlea seektoendoffile];
The following statement is used to write the contents to Fileb:
Buffer =[filehandlea readdatatoendoffile];
[Filehandleb WriteData: buffer];
Then the content of Filehandleb corresponding file is Fileb plus Filea;
12, in addition, about the location of the anchor point offset:
(1), to locate the 10th byte of a file, you can use the following method (assuming the file's handle is Xxxhandle):
[Xxxhandle Seektofileoffset:10];
(2), if you want to skip the 128 bytes after the current position in the file, you can use the following methods:
[Xxxhandle seektofileoffset: [xxxhandleoffsetinfile] + 128];
(3), to move back 5 integers in a file, you can use the following methods:
[Xxxhandle seektofileoffset: [xxxhandle offsetinfile]–5 * sizeof (int)];
13, Nsurl class is the HTTP address of the file to read the content, the following is an example of a Nsurl class:
...
nsurl *myurl = [Nsurl urlwithstring: @ "http://xxx.com"];
NSString *myhomepage = [NSStringstringwithcontentsofurl: Myurl
Encoding: Nsasciistringencoding Error:NULL];
...
OC Foundation 14: Working with files