打開檢視檔案
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.",nil),
[NSLocalizedString(@"Yes",nil),
[NSLocalizedString(@"No",nil),
nil);
if(n==NSAlertDefaultReturn){
[theManager removeFileAtPath:theFilePath handler:nil];
建立檔案夾
NSString *theDestination=[[NSHomeDirectory()
stringByAppendingPathComponent:@"Desktop"]
stringByAppendingPathComponent:@"MyNewFolder"];
[theManager createDirectoryAtpath:theDestination
attributes:nil]; //第二個參數設定檔案夾的屬性