zoukankan      html  css  js  c++  java
  • 获取文件的路径,即获取documents的路径

    1. NSSearchPathForDirectoriesInDomains和NSHomeDirectory
    iPhone和symbian 3rd一样,会为每一个应用程序生成一个私有目录,这个目录位于/Users/sundfsun2009/Library/Application Support/iPhone Simulator/User/Applications下,并随即生成一个数字字母串作为目录名,在每一次应用程序启动时,这个字母数字串都是不同于上一次。

    通常使用Documents目录进行数据持久化的保存,而这个Documents目录可以通过 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserdomainMask,YES) 得到,代码如下:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // NSString *path = [documentsDirectory stringByAppendingPathComponent:@"aa.plist"];

    NSLog(@"path: %@",path);

    打印结果如下:

    path: /Users/apple/Library/Application Support/iPhone Simulator/4.3/Applications/550AF26D-174B-42E6-881B-B7499FAA32B7/Documents

    而这个目录还可以通过 NSHomeDirectory()来得到,代码如下:

    NSString *destPath = NSHomeDirectory();
    NSLog(@"path: %@",destPath);
    //destPath = [destPath stringByAppendingPathComponent: @"Documents"];
    //NSString *xmlpath = [destPath stringByAppendingPathComponent: @"menu/menu.xml"];

    打印结果如下:

    path: /Users/apple/Library/Application Support/iPhone Simulator/4.2/Applications/6F4BC466-C5D6-440C-BAAC-BE20FA468C61

    看看两者打印出来的结果,我们可以看出这两种方法的不同。

    在documents的路径下创建文件。

    首先要获取documents的路径,如上第6条。

    其次就是下面的语句了:

    NSString *writePath=[NSString stringWithFormat:@"%@/%@.txt",documentsPath,@"aaa"];
    NSData *data = [@"" dataUsingEncoding:NSUTF8StringEncoding];//新文件的初始数据,设为空
    [[NSFileManager defaultManager] createFileAtPath:writePath contents:data attributes:nil];//创建文件的命令在这里

    这样就可以在documents文件夹下创建一个aaa.txt的文件了。哈哈哈哈哈。

    或者是用下面的语句,

    NSString *writePath=[NSString stringWithFormat:@"%@/%@.txt",documentsDirectory,@"bbb"];
    NSError *error;
    [@"fasdfasdasddaa" writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

    这样就可以在documents文件夹下创建一个bbb.txt的文件了。并且,文件中的有"fasdfasdasddaa"字符。

    总结起来就是,先给要存储的东西取一个名字,然后,找到它的路径。然后以这个名字创建。创建的时候可以添加内容

  • 相关阅读:
    dotnet core 3.0 linux 部署小贴士
    Akka.net 性能测试兼使用小技巧
    如何给小学生讲清楚ECC椭圆曲线加密
    Typescript骚操作,在TS里面直接插入HTML
    源自于NEO的KeyValue 数据库面世啦
    编译ROCKSDB总结
    Windows linux子系统 使用说明
    dotnetcore http服务器研究(二)性能分析
    dotnetcore Http服务器研究(一)
    使用信号量来 限制无边界池子与队列
  • 原文地址:https://www.cnblogs.com/gaoxiao228/p/2483542.html
Copyright © 2011-2022 走看看