{
@autoreleasepool
{
// 获取主目录,ios app 只能在这里创建删除文件
NSString *strPath = NSHomeDirectory()
// 模拟器会显示这个路径
// /Users/xxx/Library/Application Support/iPhone Simulator/7.1/Applications/82BD6DF8-0E94-4C73-B7E0-A4A0ED7C80E9
// 在桌面选择菜单上的 -> 前往 -> 前往文件夹 -> 输入这个路径就可以看到里面的文件
// 里面目录的作用可以搜索(ios沙盒机制)学习
NSLog(@"%@",strPath)
// 设置要创建文件的路径
NSString *strTxtPath= [strPath stringByAppendingPathComponent:@"test.txt"]
// 创建这个文件
NSFileManager *fileManager = [NSFileManager defaultManager]
[fileManager createFileAtPath:strTxtPath contents:nil attributes:nil]
// YES
// 可以看到 test.txt 文件
if ([fileManager fileExistsAtPath:strTxtPath])
{
NSLog(@"YES")
}
else
{
NSLog(@"NO")
}
}
return 0
}
方法:通过NSHomeDirectory获得文件路径代码如下:
NSString *homeDirectory = NSHomeDirectory()
NSString *fileDirectory = [homeDirectory stringByAppendingPathComponent:@"temp/app_data.plist"]
1.//使用NSSearchPathForDirectoriesInDomains检索指定路径
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
NSString *documentsDirectory = [paths objectAtIndex:0]z
NSString *fileDirectory = [documentsDirectory stringByAppendingPathComponent:@"file.txt"]
2.//使用Foundation中的NSTemporaryDirectory函数直接返回代表temp文件夹的全路径的字符串对象
NSString *tempDirectory = NSTemporaryDirectory()
NSString *file = [tempDirectory stringByAppendingPathComponent:@"file.txt"]
实现例子如下:
NSArray *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)
NSString *docDir = [path objectAtIndex:0]
NSLog(@"filepath:%@",docDir)
NSString *str = @"hello.jpg"
NSString *filepath = [docDir stringByAppendingPathComponent:str]
//NSString *filepath = [docDir stringByAppendingPathComponent:[NSString stringWithUTF8String:"///mest.txt"]]
NSLog(@"filepath:%@",filepath)
BOOL success = [[NSFileManager defaultManager]createFileAtPath: filepath contents:nil attributes:nil]
NSLog(@"result",success)
printf("Create File:%s %s.",[filepath UTF8String], success ? "Success" : "Error")
NSString* reValue= [NSString stringWithString:@"\\"success\\""]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)