// 基本的文件操作
// 假设存在一个名为“testfile”的文件
// 在当前目录
// NSString *fName = @"testfile";
NSFileManager *fm;
NSDictionary *attr;
// 1.需要创建文件管理器的实例
fm = [NSFileManager defaultManager];
// 创建一个文档
/*
[fm createFileAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager"
contents:<#(nullable NSData *)#> attributes:<#(nullable NSDictionary<NSString *,id> *)#>]
*/
// 2.首先确认测试文件是否存在
if ([fm fileExistsAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/testfile.txt"] == NO)
{
NSLog(@"File doesn't exist!");
return 1;
}
// 3.创建一个副本
if ([fm copyItemAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/testfile.txt"
toPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/newfile.txt"
error:NULL] == NO)
{
NSLog(@"Files copy failed!");
return 2;
}
// 4.测试两个文件是否一致
if ([fm contentsEqualAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/testfile.txt"
andPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/newfile.txt"] == NO)
{
NSLog(@"Files are not equal!");
return 3;
}
// 5.重命名副本
if ([fm moveItemAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/newfile.txt"
toPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/newfile1.txt"
error:NULL] == NO)
{
NSLog(@"File rename failed!");
return 4;
}
// 6.获取 newfile2 的大小
if ((attr = [fm attributesOfItemAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/newfile1.txt"
error:NULL]) == nil)
{
NSLog(@"Couldn't get file attributes!");
return 5;
}
NSLog(@"File size is %llu bytes.",
[[attr objectForKey:NSFileSize] unsignedLongLongValue]);
// 7.最后删除原始文件
if ([fm removeItemAtPath:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/testfile.txt"
error:nil] == NO)
{
NSLog(@"All operations were successful");
}
// 8.显示新创建的文件内容
NSLog(@"%@",
[NSString stringWithContentsOfFile:@"/Users/hesland/desktop/Foundation/Foundation/NSFileManager/newfile.txt1"
encoding:NSUTF8StringEncoding
error:nil]);
|
|