#import "ViewController.h"
@interface ViewController ()
{
NSFileManager *_manager;
NSString *_document;
NSString *_str;
NSData *_data;
NSString *_path;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *homePath=NSHomeDirectory();
_document=[homePath stringByAppendingPathComponent:@"Documents"];
_manager=[NSFileManager defaultManager];
_str=@"你好大神";
_data=[_str dataUsingEncoding:NSUTF8StringEncoding];
_path=[_document stringByAppendingPathComponent:@"test.tst"];
[self creatFile];
[self creatDirectory];
[self readFile];
[self propertiOfFile];
[self changeFile];
}
- (void)creatFile{
BOOL isSuc=[_manager createFileAtPath:_path contents:_data attributes:nil];
if (isSuc) {
NSLog(@"文件創建成功");
}
}
- (void)creatDirectory{
BOOL isSuc=[_manager createDirectoryAtPath:[_document stringByAppendingString:@"/test2"] withIntermediateDirectories:YES attributes:nil error:nil];
if (isSuc) {
NSLog(@"文件夾創建成功");
}
}
- (void)readFile{
NSData *data=[_manager contentsAtPath:_path];
NSString *str1=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str1 is:%@",str1);
NSString *str2=[NSString stringWithContentsOfFile:_path];
NSLog(@"str2 is:%@",str2);
}
- (void)changeFile{
BOOL isCopy=[_manager copyItemAtPath:_path toPath:[_document stringByAppendingString:@"/test22/test.txt"] error:nil];
if (isCopy) {
NSLog(@"複製成功");
}
BOOL isSuc=[_manager moveItemAtPath:_path toPath:[_document stringByAppendingPathComponent:@"test2/test1.txt"] error:nil];
if (isSuc) {
NSLog(@"移動成功");
}
BOOL isDelete=[_manager removeItemAtPath:_path error:nil];
if (isDelete) {
NSLog(@"刪除成功");
}
}
- (void)propertiOfFile{
NSDictionary *attributes=[_manager attributesOfItemAtPath:_path error:nil];
NSLog(@"attributes is:%@",attributes);
NSArray *subPaths=[_manager subpathsAtPath:_document];
NSLog(@"subPaths is:%@",subPaths);
NSInteger totalSize=0;
for (NSString *path in subPaths) {
NSString *subPath=[_document stringByAppendingPathComponent:path];
NSDictionary *subFileAttributes=[_manager attributesOfItemAtPath:subPath error:nil];
NSNumber *size=[subFileAttributes objectForKey:NSFileSize];
totalSize +=[size integerValue];
}
NSLog(@"totalSize is:%ld",totalSize);
}
@end