微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Cocoa文件管理

打开查看文件

NSOpenPanel *openPanel=[NSOpenPanel openPanel];

[openPanel setTitle:@"Choose a File or Folder"];//setTitle为NSWindow的方法,它是openPanel 的父类

[openPanel setCanChooseDirectories:YES];//认不可以选文件夹,可选任何格式文件

NSInteger i=[openPanel runModal];//显示openPanel

if(i==NSOKButton){

Nsstring *theFilePath=[openPanel fileName];

//给outlets(filePathdisplay)赋值:[filePathdisplay setStringValue:theFilePath]

NSFileManager *theManager=[NSFileManage defaultManager];

Nsstring *theFileName=[theManage displayNameAtPath:theFilePath];

if([theManager fileExistsAtPath:theFilePath]){

//文件存在

}

if( [theManager fileExistsAtPath:theFilePath isDirectory:&isFolder] ){

//表示选中的是一个目录(文件夹)

}

NSDictionary *theFileAttributes=[theManager fileAttributesAtPath:theFilePath traverseLink:YES];

//NSDictionary是一个数据结构,其中包括文件大小,创建日期,修改日期

//由于只是读数据,则不用可变的NSMutableDictionary

NSNumber *theFileSize=[theFileAttributes objectForKey:NSFileSize];

NSDate *theModificationDate=[theFileAttributes objectForKey:NSFileModificationDate];

NSDate *theCreationDate=[theFileAttributes objectForKey:NSFileCreationDate];

 

//查看文件图标(要先用NSFileWrapper把文件数据放入内存)

NSFileWrapper *theFileWrapper=[[NSFileWrapper alloc] initWithPath:theFilePath] autorelease];

NSImage *theIcon=[theFileWrapper icon];

//fileIcondisplay为Interface上的NSImageView对象(Library中的Image well)

[fileIcondisplay setimageScaling:NSScaletoFit];

[fileIcondisplay setimage:theIcon];

}

 

可以实现对对文档(Text),图片,以及多媒体文件的操作

复制文件

Nsstring *theDestination=[[NSHomeDirectory() //NSHomeDirectory是Foundation的方法

stringByAppendingPathComponent:@"Desktop"] //文件保存的目录

stringByAppendingPathComponent:theFileName];

[theManager copyPath:theFilePath toPath:theDestination handler:nil];

移动(剪切)文件

[theManager movePath:theFilePath toPath:theDestination handler:nil];

删除文件

NSInteger n=NSRunAlertPanel(

[NSLocalizedString(@"Are you sure you want to delete the file?",nil),

[NSLocalizedString(@"You cannot undo this deletion.",

[NSLocalizedString(@"Yes",

[NSLocalizedString(@"No",

nil);

if(n==NSAlertDefaultReturn){

[theManager removeFileAtPath:theFilePath handler:nil];

}

创建文件

Nsstring *theDestination=[[NSHomeDirectory()

stringByAppendingPathComponent:@"Desktop"]

stringByAppendingPathComponent:@"MyNewFolder"];

[theManager createDirectoryAtpath:theDestination

attributes:nil];//第二个参数设置文件夹的属性

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐