本文来讲述 文件类的各种操作方法,示例如下: NSString *fName=@"testfile.m"; NSFileManager *fm=NULL; NSDictionary *dict=NULL; fm=[NSFileManager defaultManager]; if ([fm fileExistsAtPath:fName]==NO) { NSLog(@"file not exist!"); return 1; } if ([fm copyPath:fName toPath:@"newfile" handler:nil]==NO) { NSLog(@"copy failed!"); } if ([fm movePath:@"newfile" toPath:@"newfolder" handler:nil]==NO) { NSLog(@"move failed"); } if ((dict=[fm fileAttributesAtPath:@"newfolder" traverseLink:NO])==nil) { NSLog(@"get file attributes failed"); } NSLog(@"file size is %i bytes",[[dict objectForKey:NSFileSize] intValue]); if ([fm removeFileAtPath:@"newfolder" handler:nil]==YES) { NSLog(@"remove successful!"); } NSData类的使用方法 NSData *fileData=NULL; fm=[NSFileManager defaultManager]; fileData=[fm contentsAtPath:@"testfile.m"]; if (fileData==nil) { NSLog(@"read file failed!"); } if ([fm createFileAtPath:@"file2" contents:fileData attributes:nil]==YES) { NSLog(@"create file success!"); } 对路径的操作方法: NSString *fName=@"testDir"; NSFileManager *fm=NULL; //NSDictionary *dict=NULL; NSString *path=NULL; fm=[NSFileManager defaultManager]; path=[fm currentDirectoryPath]; NSLog(@"currentDir is: %@",path); //create a new directory [fm createDirectoryAtPath:fName attributes:nil]; //rename the directory [fm movePath:fName toPath:@"newDir" handler:nil]; //change currentdirectory [fm changeCurrentDirectoryPath:@"newDir"]; path=[fm currentDirectoryPath]; NSLog(@"currentDir is: %@",path); 枚举某个目录的所有内容: NSFileManager *fm=NULL; NSDirectoryEnumerator *dirEnum=NULL; NSArray *dirArray=NULL; NSString *path=NULL; fm=[NSFileManager defaultManager]; path=[fm currentDirectoryPath]; dirEnum=[fm enumeratorAtPath:path]; while ((path=[dirEnum nextObject])!=nil) { dirArray=[fm directoryContentsAtPath:[fm currentDirectoryPath]]; } NSLog(@"%@",dirArray); NSFileHandle的使用示例: NSFileHandle *inFile, *outFile; NSData *buffer; inFile=[NSFileHandle fileHandleForReadingAtPath:@"testfile.m"]; [[NSFileManager defaultManager]createFileAtPath:@"newfile1" contents:nil attributes:nil]; outFile=[NSFileHandle fileHandleForWritingAtPath:@"newfile1"]; [outFile truncateFileAtOffset:0]; buffer=[inFile readDataToEndOfFile]; [outFile writeData:buffer]; [inFile closeFile]; [outFile closeFile];